您的位置:首页 > 其它

LeetCode进阶之路(4Sum)

2016-07-19 00:08 155 查看
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.
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点多,有时候累的真想直接躺下睡觉,但是一想,现在不努力,以后还会有机会吗?咬咬牙还是把这个任务完成了再睡,至少熟悉下题目,思考一会。


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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: