Share my simple Java solution, worst case O(n^3)


  • 0
    X
     public List<List<Integer>> fourSum(int[] nums, int target) {
            Arrays.sort(nums);
            Map<Integer, List<Point>> map = new HashMap<>();
            for (int i = 0; i < nums.length; i++) {
                if (i > 0 && nums[i] == nums[i - 1]) continue;
                for (int j = i + 1; j < nums.length; j++) {
                    int sum = nums[i] + nums[j];
                    if (!map.containsKey(sum)) {
                        map.put(sum, new ArrayList<>());
                    }
                    map.get(sum).add(new Point(i, j));
                    while (j < nums.length - 1 && nums[j] == nums[j + 1]) j++;
                }
            }
            List<List<Integer>> res = new ArrayList<>();
            for (int i = 2; i < nums.length; i++) {
                for (int j = i + 1; j < nums.length; j++) {
                    int sum = nums[i] + nums[j];
                    if (map.containsKey(target - sum)) {
                        for (Point p : map.get(target - sum)) {
                            if (p.y < i) {
                                if (nums[i] == nums[i - 1] && i - 1 != p.y) continue;
                                res.add(Arrays.asList(nums[p.x], nums[p.y], nums[i], nums[j]));
                            }
                        }
    
                    }
                    while (j < nums.length - 1 && nums[j] == nums[j + 1]) j++;
                }
            }
    
            return res;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.