leetcode解题之 18. 4Sum Java版(结果是目标值的四个数字和)

18. 4Sum

Given an array S of n integers, are there elements a, b, c, 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.

给一个数组,和一个target整数,求数组中能够使得和为target的所有组合a,b,c,d并满足a<=b<=c<=d

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]
]
参考:3sum 

public List<List<Integer>> fourSum(int[] nums, int target) {
		List<List<Integer>> ret = new ArrayList<>();

		if (nums == null || nums.length < 3)
			return ret;
		int len = nums.length;
		Arrays.sort(nums);
		// 注意,对于 num[i],寻找另外两个数时,只要从 i+1 开始找就可以了。
		// 这种写法,可以避免结果集中有重复,因为数组时排好序的,
		// 所以当一个数被放到结果集中的时候,其后面和它相等的直接被跳过。
		for (int i = 0; i < len; i++) {
			// 避免重复!!!!
			if (i > 0 && nums[i] == nums[i - 1])
				continue;
			for (int j = i + 1; j < len; j++) {
				// 注意j
				if (j > i + 1 && nums[j] == nums[j - 1])
					continue;
				// 往后找,避免重复
				int begin = j + 1;
				int end = len - 1;
				while (begin < end) {
					int sum = nums[i] + nums[j] + nums[begin] + nums[end];
					if (sum == target) {
						List<Integer> list = new ArrayList<>();
						list.add(nums[i]);
						list.add(nums[j]);
						list.add(nums[begin]);
						list.add(nums[end]);
						ret.add(list);
						begin++;
						end--;
						// 避免重复!!!!
						while (begin < end && nums[begin] == nums[begin - 1])
							begin++;
						while (begin < end && nums[end] == nums[end + 1])
							end--;
					} else if (sum > target)
						end--;
					else
						begin++;
				}
			}
		}
		return ret;
	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值