首页 > 代码库 > Two Sum - Less than or equal to target Lintcode

Two Sum - Less than or equal to target Lintcode

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.

Have you met this question in a real interview? 
Yes
Example

Given nums = [2, 7, 11, 15], target = 24
Return 5
2 + 7 < 24
2 + 11 < 24
2 + 15 < 24
7 + 11 < 24
7 + 15 < 25

这道题自己乱写了半天。。。但是屡清思路的话就很简单。。。= =
把数组排序。先把首尾相加,如果小于等于target,就说明每个数和第一个数相加都是小于target的,这个时候count += end - start。此时需注意把start往前挪一位继续进行计算。如果大于target,就说明最后一个数太大了,往前挪一个。
另外注意一下终止条件,一开始写的是start + 1 < end,但是这样子start + 1 == end的时候不会判断,所以条件是start < end。
回顾一下吧,思路还比较巧妙。
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 < 2) {
            return 0;
        }
        Arrays.sort(nums);
        int start = 0;
        int end = nums.length - 1;
        int count = 0;
        while (start < end) {
            if (nums[start] + nums[end] <= target) {
                count += end - start;
                start++;
            } else {
                end--;
            }
        }
        return count;
    }
}

 

Two Sum - Less than or equal to target Lintcode