三數之和

Leecode刷題

  • 題目描述

給定一個包含 n 個整數的數組 nums,判斷 nums 中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?找出所有滿足條件且不重複的三元組。
注意:答案中不可以包含重複的三元組。

  • 示例

例如, 給定數組 nums = [-1, 0, 1, 2, -1, -4],
滿足要求的三元組集合爲:
[
[-1, 0, 1],
[-1, -1, 2]
]

  • 代碼
class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) 
    {
        if(nums.empty()) return {};
        sort(nums.begin(),nums.end()); 
        int len = nums.size(); 
        vector<vector<int>> ans; 
        for(int i = 0;i < len;++i){
            if(i > 0 && nums[i] == nums[i-1]) continue;
            int newtar = -nums[i];//轉換成兩數之和的目標值
            int j = i + 1;
            int k = len-1;
            while(j < k)
            {
                if(nums[j] + nums[k] == newtar)
                {
                    ans.push_back({nums[i],nums[j],nums[k]});
                    while(j < k && nums[j] == nums[j + 1]) ++j;
                    while(j < k && nums[k] == nums[k - 1]) --k;
                    j++;
                    k--;
            }
            else if(nums[j] + nums[k] < newtar) j++;
            else k--;
            }
        }
    return ans;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章