LeetCode----- 15.3Sum

来源:互联网 发布:淘宝双11 销量冠军 编辑:程序博客网 时间:2024/06/05 01:00

Given an array S of n integers, are there elements abc 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]]
给定n个整型的数组,元素a,b,c,使得a+b+c=0吗?在数组中找到所有唯一的三联,他们的和等于零。

解题思路:

第一种思路:暴力解法,先排序,然后3层for循环找到相应的三个元素值。但是这种思路,时间复杂度为O(N^3),在Leetcode上会出现TLE,因此本题不适合采用该思路。


第二种思路:先将数组进行排序,循环遍历只需要到数组中的倒数第三个数就行,先固定一个数,用start,end变量分别指向固定数之后的首尾,然后在这个固定数后面相当于进行2sum查找得到target,判断固定的数与target之和是否等于0,如果等于0,将该这3个数添加到集合中;如果小于0,则start++;如果大于0,则end++。

代码如下:

public static List<List<Integer>> threeSum(int[] num) {    List<List<Integer>> list = new ArrayList<List<Integer>>();    if(num.length <3) {    return list;    }    Arrays.sort(num);    for (int i = 0; i < num.length-2; i++) {            if (i > 0 && num[i] == num[i - 1]) {                  continue;              }     int start = i+1;    int end = num.length -1;    while(start < end) {    int target =num[i]+ num[start] + num[end];    if(target == 0) {    List<Integer> result = Arrays.asList(num[i],num[start],num[end]);    list.add(result);    while(start < end && num[start] == num[start+1]){    start++;     }    while(start < end && num[end] == num[end -1]) {    end--;    }    start++;    end--;    }else if(target < 0) {    start++;    }else{    end --;    }    }}    return list;}

for循环下面的第一个if语句判断,是解决元素重复的个数,如果与前一位元素相同应该跳过当前的操作。




原创粉丝点击