15. 3Sum(字典) (双指针)

 

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]
]
 
 1 class Solution {
 2 public:
 3     vector<vector<int>> threeSum(vector<int>& nums) {
 4         
 5         sort(nums.begin(),nums.end());
 6         vector<vector<int>> res;
 7         if (nums.size() < 3) return res;
 8         for (int i = 0;i < nums.size()-1;++i) {
 9             if(i>0 && nums[i]==nums[i-1]) continue;
10             int low = i+1;
11             int high = nums.size() -1;
12             while(low < high) {
13                 int sum = nums[i] + nums[low] + nums[high];
14                 if (sum == 0) {
15                     res.emplace_back(vector<int>({nums[i],nums[low],nums[high]}));
16                     while(low<high && nums[low+1]== nums[low]) low++;
17                     while(low<high && nums[high-1]== nums[high]) high--;
18                     low++;
19                     high--;
20                 } else if (sum > 0) {
21                     high--;
22                 } else if (sum < 0) {
23                     low++;
24                 }
25             }
26         }
27         return res;
28     }
29 };

 





借助 2sum中字典的应用。 时间复杂度 o(n**2)
 1 class Solution(object):
 2     def threeSum(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: List[List[int]]
 6         """
 7         if len(nums) < 3:
 8             return []
 9         nums.sort()
10         res = set()
11         for i, v in enumerate(nums[:-2]):
12             d = {}
13             for x in nums[i+1:]:
14                 if x not in d:
15                     d[-v-x] = 1
16                 else:
17                     res.add((v, -v-x, x))
18         return map(list, res)

 

posted @ 2018-07-11 22:25  乐乐章  阅读(156)  评论(0编辑  收藏  举报