Leetcode 15. Sum(二分或者暴力或者哈希都可以)

15. 3Sum
Medium

Given an array nums of n integers, are there elements abc 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]
]

题解: 三个数的和,思路就是求任意两个数的和x,然后O(n^2),再用O(1)的搜索搜索-x是否再数组内就可以了,O(1)搜索用哈希就行,或者用O(longn)的二分的方法也可以接收,我用的自带的find函数,最后也过了
 1 class Solution {
 2 public:
 3     vector<vector<int>> threeSum(vector<int>& nums) {
 4         multiset<int> left;
 5         multiset<int> right;
 6         set<vector<int>> ans;
 7         int fl = 0;
 8         for(int i = 0;i < nums.size(); i++){
 9             if(nums[i] == 0) fl++;
10             else if(nums[i]<0) left.insert(nums[i]);
11             else if(nums[i]>0) right.insert(nums[i]);
12         }
13         set<int>:: iterator lit;
14         set<int>:: iterator rit;
15         for(lit = left.begin(); lit!=left.end(); lit++){
16             rit = lit;
17             rit++;
18             for(; rit != left.end(); rit++){
19                 int tt = (*lit)+(*rit);
20                 if(right.find(-tt)!=right.end()){
21                     vector<int> New;
22                     New.push_back( (*lit));New.push_back( (*rit));New.push_back( -tt);
23                     ans.insert(New);
24                 }
25             }
26         }
27         for(rit = right.begin(); rit!=right.end(); rit++){
28             lit = rit;
29             lit++;
30             for(; lit != right.end(); lit++){
31                 int tt = (*lit)+(*rit);
32                 if(left.find(-tt)!=left.end()){
33                     vector<int> New;
34                     New.push_back( -tt);New.push_back( (*rit));New.push_back( (*lit));
35                     ans.insert(New);
36                 }
37             }
38         }
39         if(fl>=1){
40             set<int>:: iterator it;
41             for(it = left.begin(); it!=left.end(); it++){
42                 if(right.find(-(*it))!=right.end()){
43                     vector<int> New;
44                     New.push_back((*it));New.push_back(0);New.push_back(-(*it));
45                     ans.insert(New);
46                 }
47             }
48         }
49         if(fl>=3){
50             vector<int> New;
51             New.push_back(0);New.push_back(0);New.push_back(0);
52             ans.insert(New);
53         }
54         vector<vector<int>> finalans;
55         set<vector<int>>:: iterator i;
56         for(i = ans.begin(); i!=ans.end(); i++){
57             vector<int> t = (*i);
58             finalans.push_back(t);
59         }
60         return finalans;
61     }
62 };

 

posted on 2019-09-01 20:04  若流芳千古  阅读(207)  评论(0编辑  收藏  举报

导航