Medium
过两天面Yelp, k sum在最近面经里频率还行,拿来做做吧。还是处理edge case的时候卡了一下, 记一下内部的while循环要记得加上bound: left < right, 顺便再记一下这个api:
Arrays.asList(nums[i], nums[l], nums[r])
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(nums);
//[0,0,0]
for (int i = 0; i < nums.length; i++){
if (i > 0 && nums[i] == nums[i - 1]){
continue;
}
int l = i + 1;
int r = nums.length - 1;
while (l < r){
if (nums[i] + nums[l] + nums[r] == 0){
res.add(Arrays.asList(nums[i], nums[l], nums[r]));
while (l < r && nums[l] == nums[l + 1]){
l++;
}
while (l < r && nums[r] == nums[r - 1]){
r--;
}
l++;
r--;
} else if (nums[i] + nums[l] + nums[r] > 0){
r--;
} else {
l++;
}
}
}
return res;
}
}