LeetCode 15: 3 Sum
阿新 • • 發佈:2017-08-16
res leetcode sum turn arr pub new .so while
public class Solution { public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> result = new ArrayList<>(); if (nums.length < 2) { return result; } Arrays.sort(nums); for (int i = 0; i < nums.length - 2; i++) { if(i > 0 && nums[i] == nums[i - 1]) { continue; } int j = i + 1; int k = nums.length - 1; while (j < k) { if (nums[i] + nums[j] + nums[k] == 0) { result.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--; } else if (nums[i] + nums[j] + nums[k] > 0) { k--; } else { j++; } } } return result; } }
LeetCode 15: 3 Sum