领扣609. Two Sum - Less than or equal to target

Description

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. 

最暴力的解法是遍历每一对数字,若其和不超过target且之前没有查看过这对pair,结果就+1,时间复杂度O(n^2);
稍微优化一点是排序后双指针,排序并不影响结果。排完序之后,是对每一个元素(设其index为right),去遍历它的每一个左边的元素(设其index为left),如果nums[left]+nums[right]<=target,结果就+1。这样避免了去查看right后面的数据。
其实当right往左走时,left只需往右走,不需再去查看left之前的数,因为它们已经满足了nums[right]+nums[left]<=target,只需往后查看是否还有其他满足条件的left。

最后,当left与right相遇后,left前面那些小的数字的配对全部满足条件,应该再加上这些pairs数,代码如下:

class Solution:
    """
    @param nums: an array of integer
    @param target: an integer
    @return: an integer
    """
    def twoSum5(self, nums, target):
        # write your code here
        ans=0
        nums.sort()
        print(nums)
        left,right=0,len(nums)-1
        while left<=right:
            while left<right and nums[left]+nums[right]<=target: left+=1
            ans+=left
            right-=1
        ans+=left*(left-1)/2
        return(ans)

还可以每次把left固定,那么当nums[left]+nums[right]>target时,只有right左边的数有可能满足条件,故right-=1。当第一次出现nums[left]+nums[right]<=target时, (left+1)~right中所有的数都可以与left配对。那么对于这个left的配对数应该是right-left。代码如下:

class Solution:
    """
    @param nums: an array of integer
    @param target: an integer
    @return: an integer
    """
    def twoSum5(self, nums, target):
        # write your code here
        ans=0
        nums.sort()
        left,right=0,len(nums)-1
        while left<=right:
            if nums[left]+nums[right]>target:
                right-=1
            else:
                ans+=right-left
                left+=1
        return(ans)

 

posted @ 2019-11-05 13:15  热锅上的码裔  阅读(213)  评论(0编辑  收藏  举报