2024/11/19 灵茶题单 二分查找
This commit is contained in:
parent
5331e3c5b4
commit
858e0d3c3b
|
@ -0,0 +1,30 @@
|
|||
package com.cool.ling_cha_mount.binary_search;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class Num2856 {
|
||||
public int minLengthAfterRemovals(List<Integer> nums) {
|
||||
int i = nums.get(nums.size() / 2);
|
||||
int start = binarySearch(nums, i);
|
||||
int end = binarySearch(nums, i + 1);
|
||||
if (end - start > nums.size() / 2) {
|
||||
return 2 * (end - start) - nums.size();
|
||||
} else {
|
||||
return (nums.size() & 1) == 0 ? 0 : 1;
|
||||
}
|
||||
}
|
||||
|
||||
private int binarySearch(List<Integer> list, int target) {
|
||||
int left = -1;
|
||||
int right = list.size();
|
||||
while (left + 1 < right) {
|
||||
int mid = (left + right) >>> 1;
|
||||
if (target <= list.get(mid)) {
|
||||
right = mid;
|
||||
} else {
|
||||
left = mid;
|
||||
}
|
||||
}
|
||||
return right;
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue