欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Two Sum - Less than or equal to target

程序员文章站 2022-03-11 21:50:06
...

Given an array of integers, find how many pairs in the array such that their sum is less than or equal to a specific target number. Please return the number of pairs.

Example

Example 1:

Input: nums = [2, 7, 11, 15], target = 24. 
Output: 5. 
Explanation:
2 + 7 < 24
2 + 11 < 24
2 + 15 < 24
7 + 11 < 24
7 + 15 < 24

Example 2:

Input: nums = [1], target = 1. 
Output: 0. 

思路:也是利用单调性;i不动,如果nums[i] + nums[j] < target, 那么i...j 都会小于target;

public class Solution {
    /**
     * @param nums: an array of integer
     * @param target: an integer
     * @return: an integer
     */
    public int twoSum5(int[] nums, int target) {
        if(nums == null || nums.length == 0) {
            return 0;
        }
        Arrays.sort(nums);
        int count = 0;
        int i = 0; int j = nums.length - 1;
        while(i < j) {
            int sum = nums[i] + nums[j];
            if(sum > target) {
               j--; 
            } else {
                // sum <= target;
                count += j - i;
                i++;
            }
        }
        return count;
    }
}

 

相关标签: Two pointers