Compare commits
2 Commits
0dc0b10835
...
fcc6fec024
Author | SHA1 | Date |
---|---|---|
|
fcc6fec024 | |
|
06fc23ec9f |
|
@ -0,0 +1,46 @@
|
||||||
|
package com.cool.ling_cha_mount.binary_search;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author : Cool
|
||||||
|
* @date: 2024/11/12
|
||||||
|
*/
|
||||||
|
public class Num2529 {
|
||||||
|
/**
|
||||||
|
* @Author Cool
|
||||||
|
* @Date 18:50 2024/11/12
|
||||||
|
* 找到第一个0,若存在则找最后一个0的位置,类似于<a herf="https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/description/"/>
|
||||||
|
* 若找不到0,则可能是数组内所有数字都小于0,或是不存在0,则进行分类讨论
|
||||||
|
**/
|
||||||
|
public int maximumCount(int[] nums) {
|
||||||
|
int start = binarySearch(nums, 0);
|
||||||
|
if (start < nums.length && nums[start] == 0) {
|
||||||
|
int end = binarySearch(nums, 1) - 1;
|
||||||
|
return Math.max(start, nums.length - end - 1);
|
||||||
|
}
|
||||||
|
if (start < nums.length) {
|
||||||
|
return Math.max(start, nums.length - start);
|
||||||
|
}
|
||||||
|
return nums.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int binarySearch(int[] nums, int target) {
|
||||||
|
int left = 0;
|
||||||
|
int right = nums.length - 1;
|
||||||
|
while (left <= right) {
|
||||||
|
int mid = left + (right - left) / 2;
|
||||||
|
if (target <= nums[mid]) {
|
||||||
|
right = mid - 1;
|
||||||
|
} else {
|
||||||
|
left = mid + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return left;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void test() {
|
||||||
|
maximumCount(new int[]{-2, -1, -1, 1, 2, 3});
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue