高级农民
- 积分
- 1782
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2013-10-4
- 最后登录
- 1970-1-1
|
public class Solution {
class Pair {
int fir;
int sec;
public Pair(int fir, int sec) {
this.fir = fir;
this.sec = sec;
}
}
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<>();
if (nums.length < 4) {
return res;
}
HashMap<Integer, List<Pair>> hash = new HashMap<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length-1; i++) {
for (int j = i+1; j < nums.length; j++) {
int sum = nums[i]+nums[j];
if (!hash.containsKey(sum)) {
List<Pair> list = new ArrayList<>();
hash.put(sum, list);
}
hash.get(sum).add(new Pair(i, j));
}
}
for (int i = 0; i < nums.length-3; i++) {
if (i != 0 && nums[i] == nums[i-1]) {
continue;
}
for (int j = i+1; j < nums.length-2; j++) {
if (j != i+1 && nums[j] == nums[j-1]) {
continue;
}
int target1 = target-nums[i]-nums[j];
if (!hash.containsKey(target1)) {
continue;
}
boolean firstAdd = true;
for (Pair pair: hash.get(target1)) {
if (pair.fir <= j) {
continue;
}
if (firstAdd || nums[pair.fir] != res.get(res.size()-1).get(2)) {
firstAdd = false;
List<Integer> tmp = new ArrayList<>();
tmp.add(nums[i]);
tmp.add(nums[j]);
tmp.add(nums[pair.fir]);
tmp.add(nums[pair.sec]);
res.add(tmp);
}
}
}
}
return res;
}
} |
|