您的位置:首页 > 其它

leetcode15: 3Sum

2017-06-08 22:21 477 查看
ps:既然转向大数据,java是必须的技能。所以以后的leetcode都使用java来刷题。

题目

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: 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]
]


思路:

思路一:暴力破解,时间复杂度O(N3)

思路二:针对每一个数字,找另外两个结果。

trick:考虑都是0的情况。

测试集

nums = []
nums = [1, 4, 65, -1, 2, 6, -23, 0, -4, 8]
nums = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0...., 0]
nums = [1, 2]


代码

package leetcodeArray;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Arrays;
/**
*  leetcode 15题, 3sum
*  主要考核数组的算法
* @author wq
*
*/
public class Sum3Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>>  result = new  LinkedList<List<Integer>> ();
if(nums.length < 3){
return result;
}
Arrays.sort(nums);

for(int i  = 0; i <  nums.length - 2; i++){
if(i == 0 || ( i > 0 && nums[i] != nums[i-1])){
int low = i+1;int high = nums.length - 1; int iSum = 0 - nums[i];
while(low < high){
if(nums[low] + nums[high] == iSum){
result.add(Arrays.asList(nums[i], nums[low], nums[high]));
while(low < high && nums[low] == nums[low+ 1]) low++;
while(low < high && nums[high] == nums[high - 1]) high--;
low++; high--;
}
else if( nums[low] + nums[high] > iSum){
high--;
}
else{
low++;
}
}
}
}

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