Posted onInLeetcode
,
Two point Symbols count in article: 1.4kReading time ≈1 mins.
Question
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets.
classSolution{ public List<List<Integer>> threeSum(int[] nums) { ArrayList<List<Integer>> res = new ArrayList<>(); if (nums == null || nums.length <= 2) return res; int n = nums.length; int i = 0; Arrays.sort(nums); while (i < n - 2) { int base = nums[i]; int left = i + 1; int right = n - 1; while (left < right) { int sum = base + nums[left] + nums[right]; if (sum == 0) { List<Integer> list = new LinkedList<>(); list.add(base); list.add(nums[left]); list.add(nums[right]); res.add(list); left = moveRight(nums, left + 1); right = moveLeft(nums, right - 1); } elseif (sum > 0) { right = moveLeft(nums, right - 1); } else { left = moveRight(nums, left + 1); } } i = moveRight(nums, i + 1); } return res; } privateintmoveLeft(int[] nums, int right){ while (right == nums.length - 1 || (right >= 0 && nums[right] == nums[right + 1])) { right--; } return right; } privateintmoveRight(int[] nums, int left){ while (left == 0 || (left < nums.length && nums[left] == nums[left - 1])) { left++; } return left; } }