LeetCode进阶之路(4Sum)

本文探讨了如何解决寻找数组中四个元素之和等于特定目标值的问题。通过使用类似于3Sum的方法,文章提供了一个详细的解决方案,并对算法进行了优化以减少重复结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an array S of n integers, are there elements abc, and d in S 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.

For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

题目:和2sum、3sum类似,求4个的和。所以可以直接套用3sum的算法,但是这种解法超过时间限制。有点晚了,先贴上代码,明天有空研究。下面的两个方法还是直接用的3Sum,没做修改。

7.19更新:重新修改3sum、2sum算法,整理了一下逻辑。

public class Solution {
    List<List<Integer>> list2 = new ArrayList<List<Integer>>();
    public List<List<Integer>> fourSum(int[] nums, int target) {
		if(nums == null || nums.length < 4) return list2;
		Arrays.sort(nums);
		for(int i = 0; i < nums.length - 3;i++) {
			if(i > 0&& nums[i] == nums[i-1])continue;
			int[] num = Arrays.copyOfRange(nums, i+1, nums.length);
			threeSum(num, target-nums[i], nums[i]);
		}
		
		return list2;
	}
	
	public void threeSum(int[] nums, int target, int startNum){
		if(nums == null || nums.length < 3) return ;
		Arrays.sort(nums);
		for(int i = 0;i < nums.length-2;i++) {
			if(i > 0 && nums[i] == nums[i-1])continue;
			int[] num = Arrays.copyOfRange(nums, i+1, nums.length);
			twoSum(num, target-nums[i], nums[i], startNum);
		}
	}
	public void twoSum(int[] nums, int target, int n, int startNum) {
		int left = 0;
		int right = nums.length -1;
		while(left < right) {
			if(left> 0 && nums[left-1] == nums[left]){
				left++;
				continue;
			} 
			if(right < nums.length -1 && nums[right + 1] == nums[right]){
				right--;
				continue;
			}
			if(nums[left] + nums[right] == target) {
				List<Integer> l = new ArrayList<Integer>();
				l.add(nums[left]);
				l.add(nums[right]);
				l.add(n);
				l.add(startNum);
				list2.add(l);
				left++;
				right--;
			}else if(nums[left] + nums[right] < target) {
				left++;
			}else {
				right--;
			}
		}
	}
}

每天下班回来都快10点了,洗澡弄完都11点多,有时候累的真想直接躺下睡觉,但是一想,现在不努力,以后还会有机会吗?咬咬牙还是把这个任务完成了再睡,至少熟悉下题目,思考一会。

种一棵树最好的时间是十年前,其次是现在!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值