LeetCode 题解工作台
正整数和负整数的最大计数
给你一个按 非递减顺序 排列的数组 nums ,返回正整数数目和负整数数目中的最大值。 换句话讲,如果 nums 中正整数的数目是 pos ,而负整数的数目是 neg ,返回 pos 和 neg 二者中的最大值。 注意: 0 既不是正整数也不是负整数。 示例 1: 输入: nums = [-2,-1…
3
题型
7
代码语言
3
相关题
当前训练重点
简单 · 二分·搜索·答案·空间
答案摘要
我们可以直接遍历数组,统计正整数和负整数的个数 和 ,返回 和 中的较大值即可。 时间复杂度 ,其中 为数组长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
给你一个按 非递减顺序 排列的数组 nums ,返回正整数数目和负整数数目中的最大值。
- 换句话讲,如果
nums中正整数的数目是pos,而负整数的数目是neg,返回pos和neg二者中的最大值。
注意: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] <= 2000nums按 非递减顺序 排列。
进阶:你可以设计并实现时间复杂度为 O(log(n)) 的算法解决此问题吗?
解题思路
方法一:遍历
我们可以直接遍历数组,统计正整数和负整数的个数 和 ,返回 和 中的较大值即可。
时间复杂度 ,其中 为数组长度。空间复杂度 。
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)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | 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) |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.