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)