1 题目描述
2 算法思路
算法:
- 初始化 左边界i = 0 ,右边界 j = len - 1
- 二分查找,当[i ,j] 碰到退出
- m = i + (j - i) / 2
- 如果nums[m] < target ,代表target在右边,i = m + 1
- 如果nums[m] > target ,代表target在左边,j = m - 1
- 如果nums[m] = target
- 查找右边界,i = m + 1
- 查找左边界,j = m - 1
- 返回值:最后返回 right - left - 1即可
取巧的一个方法
还是二分,不过由于题目给出的类型是int, 因此可以直接找到,
target - 0.5的位置i
target + 0.5的位置j
返回j - i
3 代码
class Solution {
public int search(int[] nums, int target) {
return helper(nums,target) - helper(nums,target - 1);
}
int helper(int[] nums,int target){
int i = 0;
int j = nums.length - 1;
while(i <= j){
int m = i + (j - i) / 2;
if(nums[m] <= target)
i = m + 1;
else
j = m - 1;
}
return i;
}
}
取巧
public int search(int[] nums, int target) {
return binarySearch(nums, target + 0.5) - binarySearch(nums, target - 0.5);
}
private int binarySearch(int[] nums, double target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = (right + left) >>> 1;
if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid - 1;
}
}
return left;
}
4 提交结果