Easy
题目描述
给定一个按 非递减顺序 排列的数组 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)) 的解决方案吗?
解题思路
这道题目要求统计数组中正整数和负整数的个数,并返回两者的最大值。由于数组已经按非递减顺序排列,我们可以利用这个性质来优化解法。
方法一:线性扫描 最直接的方法是遍历整个数组,分别统计正整数和负整数的个数。这种方法简单直观,时间复杂度为 O(n)。
方法二:二分查找(推荐) 由于数组已排序,我们可以使用二分查找来找到:
- 第一个非负数的位置(负数个数 = 该位置的索引)
- 第一个正数的位置(正数个数 = 数组长度 - 该位置的索引)
具体实现时,我们需要:
- 使用二分查找找到第一个大于等于 0 的位置,这样可以确定负数的个数
- 使用二分查找找到第一个大于 0 的位置,这样可以确定正数的个数
这种方法的时间复杂度为 O(log n),满足进阶要求。我们可以使用标准库的 lower_bound 函数来简化实现,它返回第一个不小于目标值的位置。
代码实现
class Solution {
public:
int maximumCount(vector<int>& nums) {
int negCount = lower_bound(nums.begin(), nums.end(), 0) - nums.begin();
int posCount = nums.end() - lower_bound(nums.begin(), nums.end(), 1);
return max(negCount, posCount);
}
};
class Solution:
def maximumCount(self, nums: List[int]) -> int:
import bisect
neg_count = bisect.bisect_left(nums, 0)
pos_count = len(nums) - bisect.bisect_left(nums, 1)
return max(neg_count, pos_count)
public class Solution {
public int MaximumCount(int[] nums) {
int negCount = Array.BinarySearch(nums, 0);
if (negCount < 0) negCount = ~negCount;
int posStart = Array.BinarySearch(nums, 1);
if (posStart < 0) posStart = ~posStart;
int posCount = nums.Length - posStart;
return Math.Max(negCount, posCount);
}
}
var maximumCount = function(nums) {
const binarySearch = (target) => {
let left = 0, right = nums.length;
while (left < right) {
const mid = Math.floor((left + right) / 2);
if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
};
const negCount = binarySearch(0);
const posCount = nums.length - binarySearch(1);
return Math.max(negCount, posCount);
};
复杂度分析
| 复杂度 | 时间复杂度 | 空间复杂度 |
|---|---|---|
| 二分查找法 | O(log n) | O(1) |
| 线性扫描法 | O(n) | O(1) |