标题: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
ispos
and the number of negative integers isneg
, then return the maximum ofpos
andneg
.
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;
}
};