LeetCode 259. 3Sum Smaller

Two pointers.

#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

/*
  Given an array of n integers nums and a target, find the number of index triplets i, j, k
  with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.
  For example, given nums = [-2, 0, 1, 3] and target = 2.
  return 2. Because there are two triplets which sums are less than 2.
  [-2, 0, 1]; [-2, 0, 3].
*/

int threeSumSmaller(vector<int>& nums, int target) {
  if(nums.size() < 3) return 0;
  sort(nums.begin(), nums.end());
  int count = 0;
  for(int i = 0; i < nums.size(); ++i) {
    int start = i + 1;
    int end = nums.size() - 1;
    while(start < end) {
      if(nums[i] + nums[start] + nums[end] < target) {
        count += end - start;
        start++;
      } else {
        end--;
      }
    }
  }
  return count;
}

int main(void) {
  vector<int> nums{-2, 0, 1, 3};
  cout << threeSumSmaller(nums, 2) << endl;
}


你可能感兴趣的:(LeetCode 259. 3Sum Smaller)