Leetcode - 4Sum
来源:互联网 发布:机房设计软件 编辑:程序博客网 时间:2024/06/01 17:53
public class Solution {
public List<List<Integer>> fourSum(int[] num, int target) {
List<List<Integer>> ll = new ArrayList<List<Integer>>();
if (num.length < 4)
return ll;
Arrays.sort(num);
for(int i=0; i<num.length-3; i++){
if(i>0 && num[i]==num[i-1])
continue;
for(int j=i+1;j<num.length-2;j++){
if(j>i+1 && num[j]==num[j-1])
continue;
int l=j+1, r=num.length-1;
if(l>j+1 && num[l]==num[l-1]){
l++;
continue;
}
if(r<num.length-1 && num[r]==num[r+1]){
r--;
continue;
}
while(l<r){
if(num[i]+num[j]+num[l]+num[r] == target){
List<Integer> list = new ArrayList<Integer>();
list.add(num[i]);
list.add(num[j]);
list.add(num[l++]);
list.add(num[r--]);
if(!ll.contains(list))
ll.add(list);
}else if(num[i]+num[j]+num[l]+num[r] > target){
r--;
}else
l++;
}
}
}
return ll;
}
public List<List<Integer>> fourSum(int[] num, int target) {
List<List<Integer>> ll = new ArrayList<List<Integer>>();
if (num.length < 4)
return ll;
Arrays.sort(num);
for(int i=0; i<num.length-3; i++){
if(i>0 && num[i]==num[i-1])
continue;
for(int j=i+1;j<num.length-2;j++){
if(j>i+1 && num[j]==num[j-1])
continue;
int l=j+1, r=num.length-1;
if(l>j+1 && num[l]==num[l-1]){
l++;
continue;
}
if(r<num.length-1 && num[r]==num[r+1]){
r--;
continue;
}
while(l<r){
if(num[i]+num[j]+num[l]+num[r] == target){
List<Integer> list = new ArrayList<Integer>();
list.add(num[i]);
list.add(num[j]);
list.add(num[l++]);
list.add(num[r--]);
if(!ll.contains(list))
ll.add(list);
}else if(num[i]+num[j]+num[l]+num[r] > target){
r--;
}else
l++;
}
}
}
return ll;
}
}
===================================
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.
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)
0 0
- 【Leetcode】4Sum (Sum)
- leetcode 2 sum 3sum 4sum
- Leetcode 2SUM-3SUM-4SUM
- Leetcode-2sum,3sum,4sum
- leetcode 2 sum & 3 sum & 4 sum
- [LeetCode] 2Sum, 3Sum, 4Sum, 3SUm closet
- [LeetCode] K sum(2Sum、3Sum、4Sum)
- leetcode--sum集合:2sum,3sum,4sum
- leetcode --- 2 sum , 3 sum , 4 sum , k sum problem
- LeetCode: 4 Sum
- LeetCode: 4Sum
- LeetCode 4Sum
- Leetcode: 4SUM
- 【leetcode】 4 sum
- LeetCode 4Sum
- leetcode 44: 4Sum
- [Leetcode] 4 Sum [Unsolved]
- 【leetcode】4Sum
- 使用 Codec Engine 的 API 函数(八)
- mysql 学习笔记_01
- hibernate持久类映射时对不同数据库的主键产生策略
- MapReduce的用法
- Java之equals和==详解
- Leetcode - 4Sum
- python 学习笔记——python 装饰器(二)
- 学习C++——const的用法
- 进程调度和进程时间
- CF24D 概率DP
- java简单工厂模式
- 中国最大机器人展将在天津举办
- Android开发—引入开源项目(gradle)
- 前端开发者的梦话