这道题我也觉得很棒,自己还是用的暴力的方法去做,然后就超时了啦,呜呜呜。。。
然后感叹一下讨论区的大佬真聪明。
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] ]
先上个反面版本。。!!这个超时了。时了。了。。。
class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { int m = nums.size(); vector<vector<int> > sumOfTwo(m, vector<int>(m, 0)); vector<vector<int> > res; int dup = 0; vector<int> Array(3,0); for(int k = 0; k < m; k++){ for(int i = k + 1; i < m; i++){ for(int j = i + 1; j < m; j++){ dup = 0; sumOfTwo[i][j] = nums[i] + nums[j]; Array[0] = nums[k]; Array[1] = nums[i]; Array[2] = nums[j]; sort(Array.begin(), Array.end()); for(int m = 0; m < res.size(); m++){ //这个查重超时了 if (res[m][0] == Array[0] && res[m][1] == Array[1] && res[m][2] == Array[2]) dup = 1; } if (sumOfTwo[i][j] + nums[k] == 0 && dup == 0){ res.push_back(Array); } } } } return res; } };
接下来给大佬递茶:
解析:这个就是先排序一遍,再扫描,对于 3 Sum中的每一个数字:碰到一样的就跳过;
这个是双指针的算法,刷题到现在我的感觉就是:
扫描一遍做不出来答案,看看是不是DP和递归?
超时做不出来?看看双指针或者DP= = 好多预处理都是排序啊,排序赛高!!!
class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int> > res; sort(nums.begin(), nums.end()); for(int i = 0; i < nums.size(); i++){ int front = i + 1; int back = nums.size() - 1; int target = -1 * nums[i]; while(front < back){ int sum = nums[front] + nums[back]; if(sum < target) front++; else if(sum > target) back--; else{ res.push_back({nums[i], nums[front], nums[back]}); //C++11万岁- - int tempFront = nums[front]; int tempBack = nums[back]; while(front < back && nums[front] == tempFront) front++; while(front < back && nums[back] == tempBack) back--; } } while(i+1<nums.size() && nums[i] == nums[i+1]) i++; } return res; } };