2024/11/12 灵茶题单 二分查找
This commit is contained in:
parent
0dc0b10835
commit
06fc23ec9f
|
@ -0,0 +1,40 @@
|
||||||
|
package com.cool.ling_cha_mount.binary_search;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author : Cool
|
||||||
|
* @date: 2024/11/12
|
||||||
|
*/
|
||||||
|
public class Num2529 {
|
||||||
|
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