Given an array S of n integers, are there elements a, b, c in S 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.code
For example, given array S = [-1, 0, 1, 2, -1, -4],排序
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]three
先創建hash表,而後兩層遍歷,查找第三個餘數是否存在。餘數直接用sum減去前兩個的和。
先作好排序,nlogn比n^2小不少,多作一次不影響。
遍歷時,若是發現要求的第三個數已經比第二個數小,就能夠跳事後續了,由於不可能找到了。即因爲有序,這三個數是在排序後的數組有序且遞增的。
若是第一個數就大於0,則總體確定大於0,能夠所有跳事後續。
考慮作去重,因爲有序,在同一個第一個數下,當前的第二個數若是等於上一次的第二個數,則總體必定相同,能夠跳過。ip
耗時:55mselement
class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int> > ret; if (nums.size() == 0) return ret; sort(nums.begin(), nums.end()); std::unordered_map<int,int> map; for (int i = 0; i < nums.size(); i++) { map[nums[i]] = i; } for (int i = 0; i < nums.size() - 2; i++) { if (nums[i] > 0) return ret; if (i>0 && nums[i] == nums[i-1]) continue; for (int j = i+1; j < nums.size() - 1; j++) { if (j-1>i && nums[j]==nums[j-1]) continue; int two = nums[i] + nums[j]; if (-two < nums[j]) break; if (two > 0) return ret; auto it = map.find(-two); if (it!= map.end() && it->second > j) { vector<int> r; r.push_back(nums[i]); r.push_back(nums[j]); r.push_back(-two); ret.push_back(r); } } } return ret; } };