Created
June 29, 2019 07:16
-
-
Save Desolve/075ff6e7224a53d85c2acaf0c6b73b6e to your computer and use it in GitHub Desktop.
0015 3Sum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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