3 sums題解

題幹:
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:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
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)

Difficulty: Medium
翻譯:
給一個數列和一個目標target,找三個數,相加之和是target,並且三個數不能是重複點,要遞增順序
分析:
sum系列題的第二道,跟2sum和4sums是承上啓下的作用,實際上這題有兩種解法,一種是轉化成上一道題,不過外面套一個for循環,然後把問題轉化爲2sum,另一種解法是用三個指針,一個指針指向當前元素,定位num1,另外兩個指針在num1-(n-1)的位置兩頭開始,往中間走,找num2和num3,兩種方法的唯一區別就在於是否利用輔助空間,時間複雜度都是一樣的O(n²)
sum系列一共有4道題,我們這兩道用map,下兩道用指針:

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> ret;
        if (nums.size() <= 2)
            return ret;
        map<int, int> Hash_map;
        sort(nums.begin(), nums.end());
        for (int i = 0; i < nums.size(); i++)
            Hash_map[nums[i]] = i;
            //加一層for循環
        for (int i = 0; i < nums.size(); i++) {
            int target = 0 - nums[i];
            vector<int> curr;
            //內部完全是2sum問題
            for (int j = i + 1; j < nums.size(); j++) {
                int rest_val = target - nums[j];
                if (Hash_map.find(rest_val) != Hash_map.end()) {
                    int index = nums[rest_val];
                    if (index == j || index == i) continue;
                    if (index > j) {
                        curr.push_back(nums[i]);
                        curr.push_back(nums[j]);
                        curr.push_back(nums[index]);
                        ret.push_back(curr);
                    }
                }
                while (j < nums.size() - 1 && nums[j] == nums[j + 1]) j++;
            }
            while (i < nums.size() - 1 && nums[i] == nums[i + 1]) i++;
        }
        for (int i = 0; i < ret.size(); i++) {
            if(equal(ret[i],ret[i+1]))
        }
        return ret;
    }
};

時間複雜度爲O(n²),空間複雜度爲O(n)

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