Two Sum - Less than or equal to target Lintcode

Posted 璨璨要好好学习

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

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的主要内容,如果未能解决你的问题,请参考以下文章

[LC] 1099. Two Sum Less Than K

[LeetCode] 1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold 元素和小于等于阈值的

Baozi Leetcode solution 1292. Maximum Side Length of a Square with Sum Less than or Equal to Th

leetcode_1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold_[二维前缀和](代码片段

httprunner 3.x学习18 - validate 断言总结

shell实例