leetcode 刷题-剑指offer-53题
leetcode 刷题-剑指offer-53题
题目
统计一个数字在排序数组中出现的次数。
示例 1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: 2
示例 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: 0
解答
新手上路,才学疏浅,望斧正
class Solution {
public int search(int[] nums, int target) {
if(nums.length==0){
return 0;
}
return mysearch(nums,target,0,nums.length-1);
}
public int mysearch(int[] nums,int target,int low,int hight){
int total=0;
if(hight==low ){
return nums[low]==target?1:0;
}else if(hight<low){
return 0;
} else {
int mid=(hight+low)/2;
if(nums[mid]>target){
total=total+mysearch(nums,target,low,mid-1);
}else if(nums[mid]<target){
total=total+mysearch(nums,target,mid+1,hight);
}else {
total++;
total=total+mysearch(nums,target,mid+1,hight);
total=total+mysearch(nums,target,low,mid-1);
}
}
return total;
}
}