腾讯五十题 No.9
作者:互联网
刚开始感觉哇这代码好长,还总写漏,但是写了几遍后感觉好了很多
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
//先排序
Arrays.sort(nums);
//开始遍历
for (int i = 0; i < nums.length; i++) {
if (nums[i] > 0) {
return result;
}
//nums[i]去重
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
//左右指针
int left = i + 1;
int right = nums.length - 1;
while (right > left) {
int sum = nums[i] + nums[left] + nums[right];
if (sum > 0) {
right--;
} else if (sum < 0) {
left++;
} else {
result.add(Arrays.asList(nums[i], nums[left], nums[right]));
//元素去重
while (right > left && nums[right] == nums[right - 1]) right--;
while (right > left && nums[left] == nums[left + 1]) left++;
//每轮移动左右指针
right--;
left++;
}
}
}
return result;
}
}
标签:right,nums,int,++,result,腾讯,五十,No.9,left 来源: https://www.cnblogs.com/jianjiana/p/15864854.html