首页 > 代码库 > 015. 3Sum

015. 3Sum

 1 class Solution { 2 public: 3     vector<vector<int>> threeSum(vector<int>& nums) { 4         vector<vector<int>> result; 5     //set<vector<int>> temp; 6         if (nums.size() < 3) return result; 7         else { 8             sort(nums.begin(), nums.end()); 9             for (int i = 0; i < nums.size() - 2; ++i) {10                 if (i != 0 && nums[i] == nums[i - 1]) continue;11                 int j = i + 1, k = nums.size() - 1;12                 while (i < j && j < k) {13                     if (nums[i] + nums[j] + nums[k] == 0) {14                         result.push_back(vector<int>{nums[i], nums[j], nums[k]});15                         ++j; --k;16                         while (nums[j] == nums[j - 1] && j < k) ++j;17                         while (nums[k] == nums[k + 1] && j < k) --k;18                     }19                     else if (nums[i] + nums[j] + nums[k] > 0) {20                         --k;21                         while (nums[k] == nums[k + 1] && j < k) --k;22                     }23                     else {24                         ++j;25                         while (nums[j] == nums[j - 1] && j < k) ++j;26                     }27                 }28             }29             //result = vector<vector<int>>(temp.begin(), temp.end());30             return result;31         }32     }33 };

 

015. 3Sum