扫描一遍
class Solution {
public int search(int[] nums, int target) {
int ans = 0;
for(int i = 0; i < nums.length; i ++){
if(nums[i] == target) ans ++;
}
return ans;
}
}
二分
第一次出现和最后一次出现的位置
class Solution {
public int search(int[] nums, int target) {
if(nums.length == 0) return 0;
int l = 0;
int r = nums.length - 1;
//找到第一个点
while(l < r){
int mid = l + r >> 1;
if(nums[mid] < target) l = mid + 1;
else r = mid;
}
if(nums[l] != target) return 0;
int left = l;
l = 0;
r = nums.length - 1;
while(l < r){
int mid = l + r + 1 >> 1;
if(nums[mid] <= target) l = mid;
else r = mid - 1;
}
return r - left + 1;
}
}