2824.cpp (728B)
1 // Brute force 2 class Solution { 3 public: 4 int countPairs(const vector<int> &nums, int target) const { 5 const int n = size(nums); 6 int res = 0; 7 8 for (int i = 0; i < n; i++) { 9 for (int j = 0; j < i; j++) { 10 res += nums[i] + nums[j] < target; 11 } 12 } 13 14 return res; 15 } 16 }; 17 18 // Two pointer 19 class Solution { 20 public: 21 int countPairs(vector<int> &nums, int target) const { 22 int i = 0, j = size(nums) - 1; 23 int res = 0; 24 25 sort(begin(nums), end(nums)); 26 while (i < j) { 27 if (nums[i] + nums[j] < target) 28 res += j - i, i++; 29 else 30 j--; 31 } 32 33 return res; 34 } 35 };