统计字母出现次数
输入: nums = [5,7,7,8,8,10], target = 8 (有序数组)
输出: 2
1.暴力解题
没有利用到有序的条件
class Solution {
public int search(int[] nums, int target) {
int counter = 0;
for(int num:nums){
if(num==target){
counter++;
}
}
return counter;
}
}
2.二分查找(如果有时间限制必须二分查找)
class Solution {
public int search(int[] nums, int target) {
//判断边界条件
if(nums.length==0) {
return 0;
}
//寻找第一次出现的位置
int first = first(nums, target);
//寻找第二次出现的位置
int last = last(nums, target);
return last - first+1;
}
//二分查找,找到第一数字的位置
public int first(int[] nums, int target) {
int low = 0;
int high = nums.length-1;
while(low<high) {
int mid = (low+high)/2;
//[low.....mid......target]
if(target>nums[mid]) {
low = mid+1;
}else {
high = mid;
}
}
//上面是传统的二分查找代码
if(target==nums[low]) {
return low;
}
return 0;
}
//[low.....mid......high]
public int last(int[] nums, int target) {
int low = 0;
int high = nums.length-1;
while(low<high) {
//为了避免死循环向上取整,这个方法int mid = (low+high)/2+1直接背下来!!!!必须向上取整。
int mid = (low+high)/2+1;
//[low.....mid......target]
if(target>=nums[mid]) {
low = mid;
}else {
high = mid-1;
}
}
if(nums[low]==target) {
return low;
}
//返回-1是为了满足数字不存在的情况,last - first+1 = -1+0+1 = 0
return -1;
}
}