15. 3Sum

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        if (nums == null || nums.length == 0) return ans;

        Arrays.sort(nums);
        Set<List<Integer>> temp = new HashSet<>();

        for (int i = 0; i < nums.length - 2; i++){

            int start = i + 1, end = nums.length - 1;
            while (start < end){
                int sum = nums[i] + nums[start] + nums[end];
                if (sum == 0){
                    List<Integer> found = new ArrayList<>();
                    found.add(nums[i]);
                    found.add(nums[start]);
                    found.add(nums[end]);
                    temp.add(found);
                    start++;
                    end--;
                }
                else if (sum < 0){
                    start++;
                }
                else{
                    end--;
                }
            }
        }

        for (List<Integer> lst : temp){
            ans.add(lst);
        }

        return ans;
    }
}

15

.

3Sum

results for ""

    No results matching ""