Skip to content

Latest commit

 

History

History
40 lines (39 loc) · 1.51 KB

18. 4Sum.md

File metadata and controls

40 lines (39 loc) · 1.51 KB

Solution1

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> res = new ArrayList<>();
        if (nums == null || nums.length < 4) {
            return res;
        }
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 3; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            for (int j = i + 1; j < nums.length - 2; j++) {
                if (j > i + 1 && nums[j] == nums[j - 1]) continue;
                int lo = j + 1, hi = nums.length - 1;
                while (lo < hi) {
                    if (nums[i] + nums[j] + nums[lo] + nums[hi] == target) {
                        res.add(Arrays.asList(nums[i], nums[j], nums[lo], nums[hi]));
                        while (lo < hi && nums[lo] == nums[lo + 1]) lo++;
                        while (lo < hi && nums[hi] == nums[hi - 1]) hi--;
                        lo++;
                        hi--;
                    }
                    else if (nums[i] + nums[j] + nums[lo] + nums[hi] < target) {
                        lo++;
                    }
                    else {
                        hi--;
                    }
                }
            }
        } 
        return res;
    }
}

note

  • time O(n^3) space O(1) (depends on whether output is counted as space use)
  • The idea is almost same as calculating 3 sum. Basically, we just add another nested for loop and do another duplication check. The rest is same as 3 sum which is doing two way sweeping.