双指针是在有序数组或链表上常用的优化技巧,把 O(n²) 的问题优化到 O(n)。
一、移动零
publicvoidmoveZeroes(int[]nums){intnonZero=0;for(inti=0;i<nums.length;i++){if(nums[i]!=0){inttemp=nums[i];nums[i]=nums[nonZero];nums[nonZero]=temp;nonZero++;}}}二、盛最多水的容器
publicintmaxArea(int[]height){intmax=0,left=0,right=height.length-1;while(left<right){intarea=Math.min(height[left],height[right])*(right-left);max=Math.max(max,area);if(height[left]<height[right]){left++;}else{right--;}}returnmax;}三、环形链表
publicbooleanhasCycle(ListNodehead){ListNodeslow=head,fast=head;while(fast!=null&&fast.next!=null){slow=slow.next;fast=fast.next.next;if(slow==fast)returntrue;}returnfalse;}💡 觉得有用的话,点赞 + 关注【张老师技术栈】吧!