18. 4Sum

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> ans = new ArrayList<>();
        Set<List<Integer>> set = new HashSet<>();
        if (nums == null || nums.length == 0 || nums.length < 4) return ans;

        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 3; i++){
            for (int j = i + 1; j < nums.length - 2; j++){
                int left = j + 1, right = nums.length - 1;
                while (left < right){
                    int sum = nums[i] + nums[j] + nums[left] + nums[right];
                    if (sum == target){
                        List<Integer> temp = new ArrayList<>();
                        temp.add(nums[i]);
                        temp.add(nums[j]);
                        temp.add(nums[left]);
                        temp.add(nums[right]);
                        set.add(temp);

                        left++;
                        right--;
                    }
                    else if (sum > target){
                        right--;
                    }
                    else{
                        left++;
                    }
                }
            }
        }

        for (List<Integer> list : set){
            ans.add(list);
        }

        return ans;
    }
}

results for ""

    No results matching ""