leetcode15: 3Sum

来源:互联网 发布:数据是怎么传输的 编辑:程序博客网 时间:2024/06/05 14:53

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;        }}
原创粉丝点击