Leetcode015. 3sum

題目

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

解題思路

首先對數組nums排序,其次得到的結果要去重,避免出現重複的情況。
時間複雜度O(N^2),空間複雜度O(N)。

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> ret;
        sort(nums.begin(), nums.end());
        for(int i=0; i<nums.size(); ++i){
            int j=i+1, k=nums.size() -1;
            if(i&&nums[i] == nums[i-1])
                continue;
            while(j<k){
            if(nums[j]+nums[k] == -nums[i]){
                vector<int> temp;
                temp.push_back(nums[i]);
                temp.push_back(nums[j]);
                temp.push_back(nums[k]);
                ret.push_back(temp);
                ++j;
                --k;
            }
            else if(nums[j]+nums[k] < -nums[i])
                ++j;
            else
                --k;
            }
    }
    auto pos = unique(ret.begin(),ret.end());
    ret.erase(pos,ret.end());
    return ret;
    }
};

知識點

  • unique函數
    -unique的作用是從輸入序列中“刪除”所有相鄰的重複元素。 unique去除相鄰的重複元素(只保留一個),其實它並不真正把重複的元素刪除,是把重複的元素移到後面去了,然後依然保存到了原數組中,然後 返回去重後最後一個元素的地址,因爲unique去除的是相鄰的重複元素,所以一般用之前都會要排一下序。
  • sort函數
    sort(vec.begin(), vec.end())默認是升序排列。
  • erase
    ret.erase(pos) 刪除迭代器pos所指向的元素,返回一個迭代器,它指向被刪除元素後面的元素。如果p指向容器內的最後一個元素,則返回的迭代器指向容器的超出末端的下一位置,如果p本身就是指向超出末端的下一位置的迭代器,則該函數未定義。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章