LeetCode 2529. Maximum Count of Positive Integer and Negative Integer (2025/3/12 每日一题)

标题:Maximum Count of Positive Integer and Negative Integer

题目:

Given an array nums sorted in non-decreasing order, return the maximum between the number of positive integers and the number of negative integers.

  • In other words, if the number of positive integers in nums is pos and the number of negative integers is neg, then return the maximum of pos and neg.

Note that 0 is neither positive nor negative.

Example 1:

Input: nums = [-2,-1,-1,1,2,3]
Output: 3
Explanation: There are 3 positive integers and 3 negative integers. The maximum count among them is 3.

Example 2:

Input: nums = [-3,-2,-1,0,0,1,2]
Output: 3
Explanation: There are 2 positive integers and 3 negative integers. The maximum count among them is 3.

Example 3:

Input: nums = [5,20,66,1314]
Output: 4
Explanation: There are 4 positive integers and 0 negative integers. The maximum count among them is 4.

Constraints:

  • 1 <= nums.length <= 2000
  • -2000 <= nums[i] <= 2000
  • nums is sorted in a non-decreasing order.

解题思路:找出一个非降序列中正数和负数个数最大的数。看到非降序列就自然想到二分法。这题特殊的地方在于序列中可能有多个0,所以需要用到两次二分法:第一次找到第一个非负值(>=0)的位置,即可求出序列中负值的个数;第二次找到第一个正数(>0)位置,即可求出序列中正数的个数,取最大值即可。为优化时间复杂度,可以先截断操作:若第一个数字是正数,则整个序列都是正数;若最后一个数字是负数,则整个序列都是负数,返回整个序列的长度。代码如下:

class Solution {
public:
    int maximumCount(vector<int>& nums) {
        // 截断操作
        if(nums[0] > 0 || nums.back() < 0) return nums.size();
        // 保存结果
        int res = 0;

        //第一次二分法找到第一个非负数位置
        int left = 0, right = nums.size()-1;
        while(left < right) {
            int mid = (left + right) / 2;
            if (nums[mid] < 0) left = mid+1;
            else right = mid;
        }
        res = max(res, left); //更新结果

        //第二次二分法找到第一个正数位置
        right = nums.size() - 1;
        while(left < right) {
            int mid = (left + right) / 2;
            if (nums[mid] == 0) left = mid+1;
            else right = mid;
        }
        //若最后一个值还是0,则更新指针
        if (nums[right] == 0) right++;
    
        res = max(res, (int)(nums.size() - right)); //更新结果
        return res;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值