Middle-题目100：18. 4Sum

58人阅读 评论(0)

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:
Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
The solution set must not contain duplicate quadruplets.

public class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> list = new ArrayList<List<Integer>>();
Arrays.sort(nums);
for(int i = 0;i<nums.length-3;i++) {
for(int j = nums.length-1;j-i>=3;j--) {
int sum1 = nums[i]+nums[j];
int m1 = i+1,m2 = j-1;
while(m1<m2) {
int sum = sum1+nums[m1]+nums[m2];
if(sum == target) {
List<Integer> sublist = new ArrayList<Integer>();
sublist.add(nums[i]);
sublist.add(nums[m1]);
sublist.add(nums[m2]);
sublist.add(nums[j]);
if(!list.contains(sublist))
list.add(sublist);
m1++;
}
else if(sum > target)
m2--;
else // sum < target
m1++;
}
}
}
return list;
}
}  

56ms,beats 59.49%,众数57ms,4.51%
Cmershen的碎碎念：

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：64456次
• 积分：3285
• 等级：
• 排名：第10717名
• 原创：270篇
• 转载：53篇
• 译文：0篇
• 评论：8条
文章分类
阅读排行
最新评论