双指针方法
遍历对象的过程中,使用两个指针进行操作,实现相应的目的
快慢指针
经典环形链表
[LeetCode142]
待补充
对撞指针
适用于有序数组,设置数组左索引与数组右索引
代码基本流程是
public f(int[] nums){
int left = 0;
int right = nums.length-1;
while (left <= right){
left++;
//进行操作
rigth--;
}
}
[LeetCode11]
盛水最多的容器
class Solution {
public static int maxArea(int[] height) {
int max = 0,tmp =0;
int left = 0,right = height.length-1;
while (right>left){
//计算当前两指针内最大值 然后进行指针移动操作 这里应该是当时看的题解。。。
tmp = height[right]>height[left]? height[left++]*(right-left+1):height[right--]*(right-left+1);
max = max>tmp? max:tmp;
}
return max;
}
}
[LeetCode15]
三数之和
早期刷的题基本都是看的题解。。。哭了
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
int n = nums.length;
//构造有序数组
Arrays.sort(nums);
List<List<Integer>> ans = new ArrayList<List<Integer>>();
//从头开始遍历
for (int first = 0; first < n; ++first) {
if (first > 0 && nums[first] == nums[first - 1]) {
continue;
}
//从当前元素以后设置对撞指针
int third = n - 1;
int target = -nums[first];
//left++在for循环里面
for (int second = first + 1; second < n; ++second) {
if (second > first + 1 && nums[second] == nums[second - 1]) {
continue;
}
//rigth--
while (second < third && nums[second] + nums[third] > target) {
--third;
}
//对撞返回
if (second == third) {
break;
}
//找到结果以后存储
if (nums[second] + nums[third] == target) {
List<Integer> list = new ArrayList<Integer>();
list.add(nums[first]);
list.add(nums[second]);
list.add(nums[third]);
ans.add(list);
}
}
}
return ans;
}
}
[LeetCode16]
最接近的三数之和
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int lens = nums.length;
int answer = nums[0] + nums[1] +nums[2];
for (int first = 0; first < lens-2; first++) {
if (first > 0 && nums[first] == nums[first-1]){
continue;
}
int second = first+1, third = lens-1;
while (second < third){
int sum = nums[first] + nums[second] +nums [third];
if (Math.abs(target - sum) < Math.abs(target - answer))
answer = sum;
//有序数组的核心在于减少指针的移动次数 我这里本来设置的太sb了 差点搞成暴力
if (sum >target) third --;
else if (sum <target) second++;
else return answer;
}
}
return answer;
}
}
[LeetCode42]
接雨水 待补充