美文网首页
15. 3Sum[Medium]

15. 3Sum[Medium]

作者: Michael不想说话 | 来源:发表于2019-04-11 10:22 被阅读0次

    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.

    Example:

    Given array nums = [-1, 0, 1, 2, -1, -4],
    
    A solution set is:
    [
      [-1, 0, 1],
      [-1, -1, 2]
    ]
    
    #include <iostream>
    #include <vector>
    #include <algorithm>
    
    using namespace std;
    
    class Solution {
    public:
        vector< vector<int> > twoSum(vector<int>& nums, int begin, int flag) {
            vector< vector<int> > result;
            for(int i = begin + 1, j = nums.size()-1; i < j; )
            {
                if(i>begin+1&&nums[i]==nums[i-1])
                {
                    i++;
                    continue;
                }
                int target = 0 - flag;
                if(nums[i]+nums[j] == target)
                {
                    vector<int> temp;
                    temp.push_back(flag);
                    temp.push_back(nums[i]);
                    temp.push_back(nums[j]);
                    result.push_back(temp);
                    j--;
                    i++;
    
                }
                else if(nums[i]+nums[j] > target)
                {
                    j--;
                }
                else
                {
                    i++;
                }
            }
    
            return result;
        }
    
    
        vector< vector<int> > threeSum(vector<int>& nums) {
            sort(nums.begin(), nums.end());
            vector< vector<int> > result;
            for(int i = 0; i < nums.size(); i++)
            {
                if(i>0&&nums[i]==nums[i-1]) continue;
                vector< vector<int> > temp = twoSum(nums, i, nums[i]);
                result.insert(result.end(), temp.begin(), temp.end());
            }
            return result;
        }
    };
    
    Runtime: 136 ms, faster than 37.19% of C++ online submissions for 3Sum.
    Memory Usage: 22.2 MB, less than 20.34% of C++ online submissions for 3Sum.
    
    思路
    • 先排序,遍历,然后转化为2sum问题

    相关文章

      网友评论

          本文标题:15. 3Sum[Medium]

          本文链接:https://www.haomeiwen.com/subject/uwbziqtx.html