标签:-- unique discus 顺序 oat ons int start 最小值 border
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:
For example, given array S = {-1 0 1 2 -1 -4},
A solution set is:
(-1, 0, 1)
(-1, -1, 2)
要保证不出现反复的情况,当i!=0时,假设第i个数与第i-1个数同样的话,则不进行处理,直接处理第i+1个元素。这样。仅仅要保证三个数中最小的数是依照顺序递增的。那么算法找到的解就都是不反复的。
class Solution { public: vector<vector<int> > threeSum(vector<int> &num) { int Size = num.size(); vector<vector<int> > Result; if (Size < 3) { return Result; } sort(num.begin(), num.end()); for (int Index_outter = 0; Index_outter < (Size - 2); Index_outter++) { int First = num[Index_outter]; int Second = num[Index_outter + 1]; const int Target = 0; if ((Index_outter != 0) && (First == num[Index_outter - 1])) { continue; } int Start = Index_outter + 1; int End = Size - 1; while (Start < End) { Second = num[Start]; int Third = num[End]; int Sum = First + Second + Third; if (Sum == Target) { vector<int> Tmp; Tmp.push_back(First); Tmp.push_back(Second); Tmp.push_back(Third); Result.push_back(Tmp); Start++; End--; while (num[Start] == num[Start - 1]) { Start++; } while (num[End] == num[End + 1]) { End--; } } if (Sum < Target) { Start++; while (num[Start] == num[Start -1]) { Start++; } } if (Sum > Target) { End--; if (num[End] == num[End + 1]) { End--; } } } } return Result; } };
标签:-- unique discus 顺序 oat ons int start 最小值 border
原文地址:http://www.cnblogs.com/claireyuancy/p/6812427.html