Reusing the 3Sum code, my Long and Ugly JAVA code, just share for fun


  • 0
    F
    public List<List<Integer>> threeSum(int[] nums, int target) {
        int n = nums.length;
        List<List<Integer>> lists = new ArrayList<>();
        if (n < 3) {
            return lists;
        }
        int i = 0;
        while (i <= n - 3) {
            int j = i + 1;
            int k = n - 1;
            while (j < k) {
                int sum = nums[i] + nums[j] + nums[k];
                if (sum == target) {
                    lists.add(Arrays.asList(nums[i], nums[j++], nums[k--]));
                    while (j < k && nums[j] == nums[j - 1])
                        j++;
                    while (j < k && nums[k] == nums[k + 1])
                        k--;
                }
                if (sum < target) {
                    j++;
                    while (j < k && nums[j] == nums[j - 1])
                        j++;
                }
                if (sum > target) {
                    k--;
                    while (j < k && nums[k] == nums[k + 1])
                        k--;
                }
            }
            i++;
            while (i <= n - 3 && nums[i] == nums[i - 1])
                i++;
        }
        return lists;
    }
    
    public List<List<Integer>> fourSum(int[] nums, int target) {
        int n = nums.length;
        List<List<Integer>> lists = new ArrayList<>();
        if (n < 4) {
            return lists;
        }
        Arrays.sort(nums);
        int i = 0;
        while (i <= n - 4) {
            List<List<Integer>> lists1 = threeSum(Arrays.copyOfRange(nums, i + 1, n), target - nums[i]);
            for (List<Integer> list : lists1) {
                ArrayList<Integer> arrayList = new ArrayList<>(list);
                arrayList.add(0,nums[i]);
                lists.add(arrayList);
            }
            i++;
            while (i <= n - 4 && nums[i] == nums[i - 1])
                i++;
        }
        return lists;
    }

Log in to reply
 

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