LeetCode825 适龄的朋友()

LeetCode825 适龄的朋友

二分求解,考虑重复情况

class Solution:
    def numFriendRequests(self, ages: List[int]) -> int:

        ans, n, idx = 0, len(ages), {}
        ages.sort()

        for i in range(n): idx[ages[i]] = i
        for i in range(n):

            p, l, r = 0.5 * ages[i] + 7, 0, n
            while l < r:
                mid = (l + r) // 2
                if ages[mid] > p: r = mid
                else: l = mid + 1

            ans = ans + max(0, idx[ages[i]] - l)
        
        return ans
————————

LeetCode825 适龄的朋友

二分求解,考虑重复情况

class Solution:
    def numFriendRequests(self, ages: List[int]) -> int:

        ans, n, idx = 0, len(ages), {}
        ages.sort()

        for i in range(n): idx[ages[i]] = i
        for i in range(n):

            p, l, r = 0.5 * ages[i] + 7, 0, n
            while l < r:
                mid = (l + r) // 2
                if ages[mid] > p: r = mid
                else: l = mid + 1

            ans = ans + max(0, idx[ages[i]] - l)
        
        return ans