Two Sum - Less than or equal to target

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;
    }
}
发布了562 篇原创文章 · 获赞 13 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/u013325815/article/details/103741057