Leetcode 18. 4Sum [medium] [java]

  1. 4Sum
    Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:
The solution set must not contain duplicate quadruplets.

Example
在这里插入图片描述

Solution 1
Time Complexity: O(n^3), Space Complexity: O(1)
Ignored Case

  1. the numbers can be negative
    在这里插入图片描述
class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        Arrays.sort(nums);
        
        for(int i = 0; i < nums.length-3; i++) {
            if(i > 0 && nums[i-1] == nums[i])
                continue;
            int rem = target-nums[i];
            for(int j = i+1; j < nums.length-2; j++) {
                if(j > i+1 && nums[j-1] == nums[j])
                    continue;
                int start = j+1;
                int end = nums.length-1;
                while(start < end) {
                    int sum = nums[j]+nums[start]+nums[end];
                    if(sum == rem) {
                        List<Integer> quaruplet = new ArrayList<Integer>();
                        quaruplet.add(nums[i]);
                        quaruplet.add(nums[j]);
                        quaruplet.add(nums[start]);
                        quaruplet.add(nums[end]);
                        res.add(quaruplet);
                
                        start++;
                        end--;
                        while(start < end && nums[start-1] == nums[start])
                            start++;
                            
                        while(start < end && nums[end+1] == nums[end])
                            end--;
                    } else if(sum < rem) {
                        start++;
                    } else {
                        end--;
                    }
                }
            }
        }
        
        return res;
    }
}

Solution 2: recursive, suitable for any X sum requirements
Time Complexity: O(n^4), Space Complexity: O(1)

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        Arrays.sort(nums);
        dfs(res, new ArrayList<Integer>(), nums, 0, target);
        return res;
    }
    
    
    private void dfs(List<List<Integer>> res, List<Integer> candidates, int[] nums, int curIndex, int target) {
        // the size of qualified list
        if(candidates.size() == 4) {
            if(getSum(candidates) == target) {
                res.add(new ArrayList<>(candidates));
            }
            return;
        }
        
    
        
        for(int i = curIndex; i < nums.length; i++) {
            if(i > curIndex && nums[i-1]==nums[i])
                continue;
            candidates.add(nums[i]);
            if(getSum(candidates) > target && nums[i] > 0) {
                if (!candidates.isEmpty()) {
					candidates.remove(candidates.size() - 1);
				}
				return;
            }
                
            dfs(res, candidates, nums, i + 1, target);
			if (!candidates.isEmpty()) {
				candidates.remove(candidates.size() - 1);
			}
        }
        
    }
    
    private int getSum(List<Integer> candidates) {
        int sum = 0;
        for(int item: candidates)
            sum+=item;
        return sum;
    }
}

References:

  1. https://blog.csdn.net/lm2009200/article/details/76184086

Solution 3: use hash set to store the sum of two int in the array, then check if the addition of two sum equals to the target
Time Complexity: O(n^2), Space Complexity: O(n^2)

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        Set<List<Integer>> listSet = new HashSet<>();
		int n = nums.length;
		Arrays.sort(nums);
		HashMap<Integer, List<Integer[]>> hashMap = new HashMap<>();
		for(int i = 0; i < n; i++) {
			for(int j = i + 1; j < n; j++) {
				int num = nums[i] + nums[j];
				Integer[] pair = {i, j};
				if(hashMap.containsKey(num)) {
					hashMap.get(num).add(pair);
				}else {
					List<Integer[]> list = new ArrayList<>();
					list.add(pair);
					hashMap.put(num, list);
				}
			}
		}
		for(Integer integer : hashMap.keySet()) {
			if(hashMap.containsKey(target - integer)) {
				List<Integer[]> list1 = hashMap.get(integer);
				List<Integer[]> list2 = hashMap.get(target - integer);
				for(Integer[] pair1 : list1) {
					int index1 = pair1[0];
					int index2 = pair1[1];
					for(Integer[] pair2 : list2) {
						int index3 = pair2[0];
						int index4 = pair2[1];
						if(index2 < index3) {
							List<Integer> list = new ArrayList<>();
							list.add(nums[index1]);
							list.add(nums[index2]);
							list.add(nums[index3]);
							list.add(nums[index4]);
							listSet.add(list);
						}
					}
				}
			}
		}
		return new ArrayList<>(listSet);

    }
    

}

Reference

  1. https://blog.csdn.net/qq_41231926/article/details/82177660
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值