标签:排序 -- 解题思路 sort duplicate ret begin triplets hat
算法描述:
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] ]
解题思路:
重要的点:1排序;2 三个指针去重;3注意细节。
vector<vector<int>> results; sort(nums.begin(),nums.end()); for(int i=0; i < nums.size(); i++){ if(i >0 && nums[i] == nums[i-1]) continue; int low = i+1; int high = nums.size()-1; while(low < high){ if(nums[i] + nums[low] + nums[high] == 0){ vector<int> temp = {nums[i], nums[low], nums[high]}; results.push_back(temp); while(low < high && nums[low] == nums[low+1]) low++; while(low < high && nums[high] == nums[high-1]) high--; low++; high--; } else if(nums[i] + nums[low] + nums[high] < 0){ low++; } else{ high--; } } } return results; }
标签:排序 -- 解题思路 sort duplicate ret begin triplets hat
原文地址:https://www.cnblogs.com/nobodywang/p/10326700.html