您的位置:首页 > 其它

题目:四数之和

2015-09-11 00:27 330 查看

给一个包含n个数的整数数组S,在S中找到所有使得和为给定整数target的四元组(a, b, c, d)。

您在真实的面试中是否遇到过这个题?

Yes

样例

例如,对于给定的整数数组S=[1, 0, -1, 0, -2, 2] 和 target=0. 满足要求的四元组集合为:

(-1, 0, 0, 1)

(-2, -1, 1, 2)

(-2, 0, 0, 2)

注意

四元组(a, b, c, d)中,需要满足a <= b <= c <= d

答案中不可以包含重复的四元组。

标签 Expand

解题思路:
对数组排序
确定4元数组中的前2个,
用2个指针去实现加法为target-前2个数之和
public class Solution {
/**
* @param numbers : Give an array numbersbers of n integer
* @param target : you need to find four elements that's sum of target
* @return : Find all unique quadruplets in the array which gives the sum of
*           zero.
*/
public ArrayList<ArrayList<Integer>> fourSum(int[] numbers, int target) {
//write your code here
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
if (4 > numbers.length)
return res;
int tmp[] = new int[4];
Set<ArrayList<Integer>> isExit = new HashSet<>();
Arrays.sort(numbers);
for (int i = 0; i < numbers.length - 3; i++) {
tmp[0] = numbers[i];
for (int j = i + 1; j < numbers.length - 2; j++) {
tmp[1] = numbers[j];
int start = j + 1;
int end = numbers.length - 1;
int sum = target - numbers[i] - numbers[j];
while (start < end) {
int sumTwo = numbers[start] + numbers[end];
if (sum == sumTwo) {
tmp[2] = numbers[start];
tmp[3] = numbers[end];
ArrayList<Integer> tmpList = new ArrayList<>();
for(int f=0;f<4;f++){
tmpList.add(tmp[f]);
}
if (!isExit.contains(tmpList)) {
res.add(tmpList);
isExit.add(tmpList);
}
start++;
end--;
} else if ( sumTwo<sum) {
start++;
} else {
end--;
}
}

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