leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0015.cpp (930B)


      1 class Solution {
      2   public:
      3     vector<vector<int>> threeSum(vector<int> &num) {
      4         sort(num.begin(), num.end());
      5 
      6         vector<vector<int>> res;
      7         for (int i = 0; i < num.size();) {
      8             int target = -num[i], start = i + 1, end = num.size() - 1;
      9 
     10             while (start < end) {
     11                 int sum = num[start] + num[end];
     12                 if (sum < target)
     13                     start++;
     14                 else if (sum > target)
     15                     end--;
     16                 else {
     17                     res.push_back({num[i], num[start], num[end]});
     18                     while (start < end && num[start] == res.back()[1])
     19                         start++;
     20                     while (start < end && num[end] == res.back()[2])
     21                         end--;
     22                 }
     23             }
     24             for (i++; i < num.size() && num[i] == num[i - 1]; i++)
     25                 ;
     26         }
     27 
     28         return res;
     29     }
     30 };