您的位置:首页 > 编程语言 > Java开发

leetcode解题之 15. 3Sum Java版(结果为目标值的三个数字)

2017-04-06 18:29 423 查看

15. 3Sum

Given an array S of n integers, are there elementsa,
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(log(n)),然后定好一个数的位置,查找另外两个数的和等于-nums[i]的组合,由于数组排好序了,所以可以从两边往中间走,当结果大于0的时候后边往后退一步,否则前边进一步,时间复杂度O(n^2),所以时间复杂度为O(n^2)

// 避免重复!!!!
// 避免重复!!!!
// 避免重复!!!!
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> ret = new ArrayList<>();

if (nums == null || nums.length < 3)
return ret;
int len = nums.length;
Arrays.sort(nums);
// 注意,对于 num[i],寻找另外两个数时,只要从 i+1 开始找就可以了。
// 这种写法,可以避免结果集中有重复,因为数组时排好序的,
//所以当一个数被放到结果集中的时候,其后面和它相等的直接被跳过。
for (int i = 0; i < len; i++) {
// 可省,目的减少无意义的循环
if (nums[i] > 0)
break;
// 避免重复!!!!
if (i > 0 && nums[i] == nums[i - 1])
continue;
// 往后找,避免重复
int begin = i + 1;
int end = len - 1;
while (begin < end) {
int sum = nums[i] + nums[begin] + nums[end];
if (sum == 0) {
List<Integer> list = new ArrayList<>();
list.add(nums[i]);
list.add(nums[begin]);
list.add(nums[end]);
ret.add(list);
begin++;
end--;
// 避免重复!!!!
while (begin < end && nums[begin] == nums[begin - 1])
begin++;
while (begin < end && nums[end] == nums[end + 1])
end--;
} else if (sum > 0)
end--;
else
begin++;
}
}
return ret;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode 15. 3Sum