JZX轻语:简

LeetCode每日一题(20240409) - 正整数和负整数的最大计数

发表于2024年04月09日

二分搜索的简单题目,先实现一个二分搜索函数maximumCount以计算大于等于指定值target的最小值索引,然后负整数的数目为maximumCount(0)(比0小的数量),正整数的数目为n - maximumCount(1)(大于等于1的数量)。

import math

class Solution:
    def maximumCount(self, nums: List[int]) -> int:
        def binarySearch(target: int) -> int:
            """ 返回大于等于target的最小值索引 """
            nonlocal n, nums
            lo, hi = 0, n - 1
            while lo <= hi:
                mid = (lo + hi) >> 1
                if nums[mid] < target:
                    lo = mid + 1
                else:
                    hi = mid - 1
            return lo

        n = len(nums)
        neg = binarySearch(0)
        pos = n - binarySearch(1)
        return max(neg, pos)

闪念标签:LC

题目链接:https://leetcode.cn/problems/maximum-count-of-positive-integer-and-negative-integer/