LeetCode 2529.正整数和负整数的最大计数
题目:给你一个按 非递减顺序 排列的数组 nums ,返回正整数数目和负整数数目中的最大值。
- 换句话讲,如果
nums中正整数的数目是pos,而负整数的数目是neg,返回pos和neg二者中的最大值。
注意:0 既不是正整数也不是负整数。
思路:灵神 闭区间写法,>= > < <=转化
代码:
class Solution {
public int maximumCount(int[] nums) {
int posi = lowerBound(nums, 1);
int nega = lowerBound(nums, 0) - 1;
return Math.max(nega + 1, nums.length - posi);
}
private int lowerBound(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left;
}
}
性能:
时间复杂度o(logn)
空间复杂度o(1)
原文地址:https://blog.csdn.net/qq_57349657/article/details/148641467
免责声明:本站文章内容转载自网络资源,如侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!
