算法【数组】ThreeSum

/*3Sum
描述
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0 ?
Find all unique triplets in the array which gives the sum of zero.
Note:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4} .
A solution set is:
(-1, 0, 1)
(-1, -1, 2)
分析

对题目进行分析便可知此题是2sum问题的升级,对于本题的解法思路

当然 有简单的暴力算法 3重for循环 算法的时间复杂度为O(N^3)当然还可能有存在重复值的问题当然也可能会导致
超时情况存在
在此我们思考 在对数组已经进行了排序的基础上,我们考虑先固定一个数,然后再到数组内查询2个数,设置两个指针,一个
指向数组头部一个指向数组尾部 结合已经固定的数字 便可完成对3SUM问题的解答

这是解决问题的一种思路 我们同样也可以将这种思路扩展到n_SUM问题当中去  
*/

请看代码展示

public List<List<Integer>> threeSum(int[] nums,int target){
List<List<Integer>> result = new List<List<Integer>>();s
if (nums == null || nums.length<3 ) {
return null;
}
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
int j = i;
int k = nums.length-1;
while ( j < k) {
if ( nums[i] + nums[j] +nums[k] < target) {
j++;
while (nums[j] == nums[j+1] && j<k) {
j++;
}
}else if (nums[i] + nums[j] +nums[k] > target) {
k--;
while (nums[k] == nums[k-1] && j<k) {
k--;
}
}else if (nums[i] + nums[j] +nums[k] = target) {
result.add(Arrays.asList(nums[i],nums[j],nums[k]));
j++;
k--;
while (nums[j] == nums[j+1] && j<k) {
j++;
}
while (nums[k] == nums[k-1] && j<k) {
k--;
}
}
}
}
return result;

}

重点不在3SUM在于这种处理问题的思路,西安对数组排序然后左右夹逼找出符合要求的集合

我与大家一同进步 ヾ(◍°∇°◍)ノ゙加油!!!

posted @ 2018-03-22 14:30  倾城之泪  阅读(384)  评论(0)    收藏  举报