leetcode - 3Sum
2013-03-03 19:29 张汉生 阅读(140) 评论(0) 编辑 收藏 举报题目描述:点击此处
1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 class Solution { 5 public: 6 vector<vector<int> > threeSum(vector<int> &num) { 7 vector<vector<int> > result; 8 sort(num.begin(),num.end()); 9 vector<int> entry; 10 entry.assign(3,-1000); 11 vector<int>::iterator i ,j ,k; 12 for (i=num.begin();i<num.end();i++){ 13 if (i>num.begin() && *i==*(i-1)) 14 continue; 15 j = i+1; 16 k = num.end()-1; 17 while (j<k){ 18 int sum = *i+*j+*k; 19 if (sum>0) 20 k--; 21 else if (sum<0) 22 j++; 23 else { 24 if (*j!=entry[1]||*k!=entry[2]){ 25 entry[0]=*i; 26 entry[1]=*j; 27 entry[2] = *k; 28 result.push_back(entry); 29 } 30 k--; 31 j++; 32 } 33 } 34 } 35 return result; 36 } 37 };
完毕。