[LeetCode] 2824. Count Pairs Whose Sum is Less than Target

发布时间 2023-11-24 03:07:12作者: CNoodle

Given a 0-indexed integer array nums of length n and an integer target, return the number of pairs (i, j) where 0 <= i < j < n and nums[i] + nums[j] < target.

Example 1:
Input: nums = [-1,1,2,3,1], target = 2
Output: 3
Explanation: There are 3 pairs of indices that satisfy the conditions in the statement:

  • (0, 1) since 0 < 1 and nums[0] + nums[1] = 0 < target
  • (0, 2) since 0 < 2 and nums[0] + nums[2] = 1 < target
  • (0, 4) since 0 < 4 and nums[0] + nums[4] = 0 < target
    Note that (0, 3) is not counted since nums[0] + nums[3] is not strictly less than the target.

Example 2:
Input: nums = [-6,2,5,-2,-7,-1,3], target = -2
Output: 10
Explanation: There are 10 pairs of indices that satisfy the conditions in the statement:

  • (0, 1) since 0 < 1 and nums[0] + nums[1] = -4 < target
  • (0, 3) since 0 < 3 and nums[0] + nums[3] = -8 < target
  • (0, 4) since 0 < 4 and nums[0] + nums[4] = -13 < target
  • (0, 5) since 0 < 5 and nums[0] + nums[5] = -7 < target
  • (0, 6) since 0 < 6 and nums[0] + nums[6] = -3 < target
  • (1, 4) since 1 < 4 and nums[1] + nums[4] = -5 < target
  • (3, 4) since 3 < 4 and nums[3] + nums[4] = -9 < target
  • (3, 5) since 3 < 5 and nums[3] + nums[5] = -3 < target
  • (4, 5) since 4 < 5 and nums[4] + nums[5] = -8 < target
  • (4, 6) since 4 < 6 and nums[4] + nums[6] = -4 < target

Constraints:
1 <= nums.length == n <= 50
-50 <= nums[i], target <= 50

统计和小于目标的下标对数目。

给你一个下标从 0 开始长度为 n 的整数数组 nums 和一个整数 target ,请你返回满足 0 <= i < j < n 且 nums[i] + nums[j] < target 的下标对 (i, j) 的数目。

思路

对 input list 排序,然后用类似611题那种找三角形有效边的方法找下标对。

复杂度

时间O(nlogn) - sort
空间O(1)

代码

Java实现

class Solution {
    public int countPairs(List<Integer> nums, int target) {
        int res = 0;
        Collections.sort(nums);
        int left = 0;
        int right = nums.size() - 1;
        while (left < right) {
            if (nums.get(left) + nums.get(right) < target) {
                res += right - left;
                left++;
            } else {
                right--;
            }
        }
        return res;
    }
}

相关题目

259. 3Sum Smaller
611. Valid Triangle Number
2563. Count the Number of Fair Pairs
2824. Count Pairs Whose Sum is Less than Target