Home LeetCode. 15. 3Sum
Post
Cancel

LeetCode. 15. 3Sum

image

[Link] https://leetcode.com/problems/3sum/


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.util.*;

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        // for(List<Integer> e: nums) for()
        List<List<Integer>> list = new LinkedList<> ();
        for(int i = 0; i < nums.length - 2; i++) {
            if(nums[i] > 0) break;
            if(i > 0 && nums[i] == nums[i-1]) continue;
            int start = i + 1, end = nums.length - 1;
            int sum = (-1) * nums[i];
            while(start < end) {
                if(nums[start] + nums[end] > sum) end--;
                else if(nums[start] + nums[end] == sum) {
                    list.add(Arrays.asList(nums[i], nums[start], nums[end]));
                    while(start < end && nums[start] == nums[start+1]) start++;
                    while(start < end && nums[end] == nums[end-1]) end--;
                    start++;
                    end--;
                }
                else start++;
            }
        }
        return list;
    }
}
This post is licensed under CC BY 4.0 by the author.