備戰面試——算法部分leetcode Sum3

Given an array nums of n integers, are there elements abc in nums 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.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

這題就是個三數之和等於0,最容易想到的方法就是直接暴力三層循環,但這個就是來搞笑的,O(N3)

然後很容易想到的就是先排序,從小到大排序後,這樣就可以利用大小關係來篩選掉一些,然後再遍歷

我想了想,發現複雜度並沒有改變,因爲重排後我還是三層遍歷了,所以不行

然後我就沒繼續想了,直接看discussion了,結果發現排名第一的java答案跟我想的差不多,多想的那步是由於排序後,我們取第i個a和第i+1個b和第nums.length-1個元素c,如果存在a+b+c==0,那麼勢必下一個滿足三元式的解,b要往右移動,c要往左移動,因爲c是最右邊的元素,它是最大的,在a不動的情況下,它移動那麼b也必須得往又移動,不然不會滿足等式

這樣就變成了雙層循環,O(N2),而排序用的是快排,O(NlogN),所以最終複雜度O(n2)

代碼:

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> res = new LinkedList<>();
        for(int i=0;i< nums.length-2;i++){
            int lo = i+1;int hi = nums.length-1;
            if(i==0||i>0&&nums[i]!=nums[i-1]){
                while(lo<hi) {
                    if (nums[lo] + nums[hi] + nums[i] == 0) {
                                
               res.add(Arrays.asList(nums[i],nums[lo],nums[hi]));
                        while (lo<hi&&nums[hi] == nums[hi - 1]) hi--;
                        while (lo<hi&&nums[lo] == nums[lo + 1]) lo++;
                        hi--;lo++;
                    }
                    else if(nums[lo]+nums[hi]+nums[i]>0){
                        hi--;
                    }
                    else{
                        lo++;
                    }
                }
            }
        }
        return res;
    }
}

 

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