Leetcode 15. 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.

注意:

The solution set must not contain duplicate triplets.

例子:

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

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

代碼:

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        
        std::sort(nums.begin(), nums.end());
        vector<vector<int>> ret;
        for(int i = 0; i<nums.size(); i++){
            
            int target = -nums[i];
            int front = i + 1;
            int back = nums.size() - 1;
            while(front < back)
            {
                int sum = nums[front] + nums[back];
                if (sum<target){
                    front++;
                }
                else if(sum>target){
                    back--;
                }
                else{
                    vector<int> triplet(3, 0);
                    triplet[0] = nums[i];
                    triplet[1] = nums[front];
                    triplet[2] = nums[back];
                    
                    ret.push_back(triplet);
                    while(front < back && nums[front] == triplet[1]){
                    front ++;   }
                                 
                while(front < back && nums[back] == triplet[2]){
                    back --;
                }
                    
                }


            }
            while(i+1<nums.size() && nums[i+1] == nums[i]){
                i++;
            }
        }
        return ret;
    }
};

知識點:

  • 在思考數組類問題時候,可以考慮排序是否會降低複雜度。
  • 雙指針搜索的前提就是有序的數列!
  • STL中對於數組的排序std::sort(num.begin(), num.end())是一個原位置排序。

複雜度:

  • 暴力解法 n3n^3
  • 雙指針解法 n2n^2
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章