LeetCode 题解工作台

正整数和负整数的最大计数

给你一个按 非递减顺序 排列的数组 nums ,返回正整数数目和负整数数目中的最大值。 换句话讲,如果 nums 中正整数的数目是 pos ,而负整数的数目是 neg ,返回 pos 和 neg 二者中的最大值。 注意: 0 既不是正整数也不是负整数。 示例 1: 输入: nums = [-2,-1…

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 二分·搜索·答案·空间

bolt

答案摘要

我们可以直接遍历数组,统计正整数和负整数的个数 和 ,返回 和 中的较大值即可。 时间复杂度 ,其中 为数组长度。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个按 非递减顺序 排列的数组 nums ,返回正整数数目和负整数数目中的最大值。

  • 换句话讲,如果 nums 中正整数的数目是 pos ,而负整数的数目是 neg ,返回 posneg二者中的最大值。

注意:0 既不是正整数也不是负整数。

 

示例 1:

输入:nums = [-2,-1,-1,1,2,3]
输出:3
解释:共有 3 个正整数和 3 个负整数。计数得到的最大值是 3 。

示例 2:

输入:nums = [-3,-2,-1,0,0,1,2]
输出:3
解释:共有 2 个正整数和 3 个负整数。计数得到的最大值是 3 。

示例 3:

输入:nums = [5,20,66,1314]
输出:4
解释:共有 4 个正整数和 0 个负整数。计数得到的最大值是 4 。

 

提示:

  • 1 <= nums.length <= 2000
  • -2000 <= nums[i] <= 2000
  • nums非递减顺序 排列。

 

进阶:你可以设计并实现时间复杂度为 O(log(n)) 的算法解决此问题吗?

lightbulb

解题思路

方法一:遍历

我们可以直接遍历数组,统计正整数和负整数的个数 aabb,返回 aabb 中的较大值即可。

时间复杂度 O(n)O(n),其中 nn 为数组长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
class Solution:
    def maximumCount(self, nums: List[int]) -> int:
        a = sum(x > 0 for x in nums)
        b = sum(x < 0 for x in nums)
        return max(a, b)
speed

复杂度分析

指标
时间complexity is O(log N) due to two binary searches, each over the sorted array. Space complexity is O(1) because no extra data structures are used, only counters and pointers.
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Check if the candidate correctly identifies zeros as neutral and ignores them in counts.

  • question_mark

    Listen for a binary search approach instead of linear counting to assess efficiency.

  • question_mark

    Confirm if the solution correctly handles arrays with all positives or all negatives.

warning

常见陷阱

外企场景
  • error

    Counting zeros as positive or negative, which skews the result.

  • error

    Using linear scan instead of binary search, leading to O(N) time complexity.

  • error

    Off-by-one errors when computing counts from indices after binary search.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Find maximum counts in a rotated sorted array with the same positive/negative rule.

  • arrow_right_alt

    Return both counts of positive and negative integers instead of the maximum.

  • arrow_right_alt

    Handle unsorted arrays by sorting first, then applying the binary search counting approach.

help

常见问题

外企场景

正整数和负整数的最大计数题解:二分·搜索·答案·空间 | LeetCode #2529 简单