leetcode15. three digital sum (hash table unordered_map, double pointer)

Subject description:

Given an array nums n comprises integers, determines whether there are three elements a, b, c nums such that a + b + c = 0? All the conditions are not satisfied to find duplicate triples.

Note: The answer can not contain duplicate triples.

For example, given the array nums = [-1, 0, 1, 2, -1, -4],

Meet the requirements set for the triples:

[ [-1, 0, 1], [-1, -1, 2] ]

Method One: hash table

The idea is similar to two numbers and, in this question, the first two numbers are known, to find whether there is an array -ab

#include<iostream>
#include<vector>
#include<unordered_map>
#include<algorithm>
using namespace std;

class Solution{
public:
    vector<vector<int>> threeSum(vector<int>& nums){
        vector<vector<int>> result;
        if(nums.size() == 0)
            return result;
        sort(nums.begin(), nums.end());  0I =int(forarray is sorted in order to follow a weight//
        ; i<nums.size(); ++i){
            if(i!=0 && nums[i] == nums[i-1])
                continue;
            unordered_map<int, int> map;
            for(int j=i+1; j<nums.size(); ++j){
                if(map.find(-nums[i]-nums[j]) != map.end()){
                    result.push_back({nums[i], nums[j], -nums[i]-nums[j]});
                    while(j+1 < nums.size() && nums[j] == nums[j+1])
                        j++;
                }
                map.insert({nums[j], j});
            }
        }
        return result;
    }
};

int main(){
    Solution solution;
    vector<int> vec;
    int i;
    do{
        cin>>i;
        vec.push_back(i);
    }while(getchar() != '\n');
    vector<vector<int>> result;
    result = solution.threeSum(vec);
    int rows = result.size();
    int columns = result[0].size();
    for(int i=0; i<rows; ++i)
        for(int j = 0; j<columns; ++j){
            cout<<result[i][j]<<" ";
        }
    cout<<endl;
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/jiangyaju/p/11074503.html