leetcode 15 3Sum

題目詳情

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.

給定一個整數數組s,咱們要找出s中是否有三個不一樣元素的加和等於0,若是有,輸出全部知足條件的序列。要求序列不重複。數組

For example, 輸入數組S = [-1, 0, 1, 2, -1, -4],
返回的結果集應該是:
[
[-1, 0, 1],
[-1, -1, 2]
]指針

想法

  • 經過減治的思想,咱們可把三個數求和的問題,減治爲對於數組中不重複的元素nums[i],求兩個數的和等於-nums[i]的過程。
  • 這個問題比較複雜的一點是,還要處理重複的數據。爲了簡化咱們的操做,咱們先對數組進行預排序。
  • 經歷了預排序,咱們判斷一個元素是否重複,只須要比較它和以前位置的元素是否相等就能夠了。
  • 排序以後,對於求兩個數和的問題,能夠經過low和high兩個指針從兩邊查找,也簡化了操做時間。

解法

public List<List<Integer>> threeSum(int[] nums) {
        int length = nums.length;
         List<List<Integer>> res = new  ArrayList<List<Integer>>();
         Arrays.sort(nums);
        
         for(int i=0;i<length-2;i++){
             //防止重複序列
             if(i ==0 || (i>0 && nums[i] != nums[i-1])){
                 int low = i+1;
                 int high = length-1;
                 int target = -nums[i];
                 
                 while(low < high){
                     if(nums[low]+nums[high] == target){
                         res.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] < target){
                         low++;
                     }else{
                         high--;
                     }
                 }
             }
         }
        
        
        return res;
    }
相關文章
相關標籤/搜索