MCPcopy Create free account
hub / github.com/Hsinha11/Leetcode-solutions / threeSum

Method threeSum

15-3sum/3sum.java:6–34  ·  view source on GitHub ↗
(int[] nums)

Source from the content-addressed store, hash-verified

4
5class Solution {
6 public List<List<Integer>> threeSum(int[] nums) {
7 Arrays.sort(nums);
8 List<List<Integer>> result = new ArrayList<>();
9
10 for (int i = 0; i < nums.length - 2; i++) {
11 if (i > 0 && nums[i] == nums[i - 1]) continue;
12
13 int left = i + 1;
14 int right = nums.length - 1;
15
16 while (left < right) {
17 int sum = nums[i] + nums[left] + nums[right];
18
19 if (sum == 0) {
20 result.add(Arrays.asList(nums[i], nums[left], nums[right]));
21 while (left < right && nums[left] == nums[left + 1]) left++;
22 while (left < right && nums[right] == nums[right - 1]) right--;
23 left++;
24 right--;
25 } else if (sum < 0) {
26 left++;
27 } else {
28 right--;
29 }
30 }
31 }
32
33 return result;
34 }
35}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected