题目描述
统计一个数字在排序数组中出现的次数。
题目链接:https://leetcode-cn.com/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof/
最初的想法
class Solution {
public int search(int[] nums, int target) {
int mid = (nums.length - 1)>>1;
int count = 0, l = 0,r = nums.length - 1;
do{
if(nums[mid] > target) {
r = mid;
mid = (mid + l)>>1;
}
else if(nums[mid] < target) {
l = mid;
mid = (mid + r)>>1;
}
} while(nums[mid] != target);
int i = mid;
while(nums[i] == target){
count++;
i++;
}
while(nums[mid-1] == target){
count++;
mid--;
}
return count;
}
}
优化
class Solution {
public int search(int[] nums, int target) {
int i = 0, j = nums.length - 1;
while(i <= j){
int mid = (i + j) / 2;
if(nums[mid] <= target) i = mid + 1;
else j = mid - 1;
}
int right = i;
i = 0; j = nums.length - 1;
while(i <= j){
int mid = (i + j) / 2;
if(nums[mid] < target) i = mid + 1;
else j = mid - 1;
}
int left = j;
return right - left - 1;
}
}
优化题解
只要找到大于这个数的第一个的下标和小于这个数的第一个下标即可。