Skip to content

Instantly share code, notes, and snippets.

@Desolve
Created June 29, 2019 07:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Desolve/075ff6e7224a53d85c2acaf0c6b73b6e to your computer and use it in GitHub Desktop.
Save Desolve/075ff6e7224a53d85c2acaf0c6b73b6e to your computer and use it in GitHub Desktop.
0015 3Sum
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new LinkedList<>();
for (int i = 0; i < nums.length-2; i++) {
if (i == 0 || (i > 0 && nums[i] != nums[i - 1])) {
int j = i + 1, k = nums.length - 1, target = 0 - nums[i];
while (j < k) {
if (nums[j] + nums[k] == target) {
res.add(Arrays.asList(nums[i], nums[j], nums[k]));
while (j < k && nums[j] == nums[j + 1]) j++;
while (j < k && nums[k] == nums[k - 1]) k--;
j++; k--;
} else if (nums[j] + nums[k] < target) ++j;
else --k;
}
}
}
return res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment