leetcode15: 3Sum

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;
        }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章