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

Leetcode刷题记——15. 3Sum(3个数字和)

2016-11-02 16:31 274 查看
一、题目叙述:

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


Subscribe to see which companies asked this question

二、解题思路:

激动咩激动咩,我爱编程!(虽然水平非常差)。恩,经典的求和问题,即从一组数里,输出三个数和为0的所有组合列表,我们之前做过2Sum咩。一看呢就不能用暴力的方法,必然超时。所以类似于2Sum的解法

(1)主体思路:循环前两个数,然后二分查找(所以数组要先排序)为前两数和的相反数的第三个数,这样复杂度能从O(n3)减到O(n2logn)。

(2)注意:列表里不能出现相同的组合!第一次我直接在找到第三个数时候循环判断了,与之前的组合相同的不添加进列表,傻不傻,前面改善算法得来的优势又被耗掉了,显而易见会超时。最后看了别人的代码,在第一个数和第二个数的循环开头分别加入一个判断,若之前已经用过这个数了,就跳过。

三、源码:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution
{
List<List<Integer>> ans = new ArrayList<List<Integer>>();
public List<List<Integer>> threeSum(int[] nums)
{
Arrays.sort(nums);
int q;
int h;
//int count = 0;
//List<List<Integer>> reslist = new ArrayList<List<Integer>>();
for (int i = 0; i < nums.length; i ++)
{
if (i > 0 && nums[i] == nums[i-1]) continue;//去除重复
for (int j = i + 1; j < nums.length; j++)
{
if (j > i+1 && nums[j] == nums[j-1]) continue;//去除重复
q = BinarySearch(-nums[i]-nums[j], nums, j+1, nums.length - 1);
if (q > j)
{
//count ++;
List<Integer> list = new ArrayList<Integer>();
list.add(nums[i]);
list.add(nums[j]);
list.add(nums[q]);
ans.add(list);
}
}
}

return ans;
}
public int BinarySearch (int k,int[] num,int first, int last)
{
//int first = 0;
//int last = num.length - 1;
int mid;
while (first <= last)
{
mid = (first + last) / 2;
if (num[mid] > k) last =mid - 1;
else if (num[mid] < k) first = mid + 1;
else return mid;
}
return -1;
}
public static void main(String args[])
{
int[] a = {0,0,0,0};
Solution so = new Solution();
System.out.println(so.threeSum(a));

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