其他分享
首页 > 其他分享> > 剑指offer_53 在排序数组中查找数字 I

剑指offer_53 在排序数组中查找数字 I

作者:互联网

剑指 Offer 53 - I. 在排序数组中查找数字 I

统计一个数字在排序数组中出现的次数。

 

示例 1:

输入: nums = [5,7,7,8,8,10], target = 8
输出: 2

示例 2:

输入: nums = [5,7,7,8,8,10], target = 6
输出: 0

 1 int searchFirsttarget(int* nums,int length,int start,int end,int target){
 2     if(start>end) return -1;
 3     int middle = start + length/2;
 4     if(nums[middle] > target) {
 5         length = middle - start;
 6         end = middle -1;}
 7     else if(nums[middle] < target) {length = end -middle;start = middle +1;}
 8     if(nums[middle] == target ){
 9         if( middle == 0) return middle;
10         if(nums[middle-1] != target ) return middle;
11         else {length = middle-start;end = middle-1;}
12     }
13     return searchFirsttarget(nums,length,start,end,target);
14 }
15 int searchLasttarget(int* nums,int length,int start,int end,int target){
16     if(start>end) return -1;
17     int middle = start + length/2;
18     if(nums[middle] > target) {length = middle - start;end = middle -1;}
19     else if(nums[middle] < target) {length = end -middle;start = middle +1;}
20     if(nums[middle] == target){
21         if( middle == end) return middle; //⭐注意不能越界
22         if(nums[middle+1] != target || middle == end) return middle;
23         else {length = end -middle;start = middle +1;}
24     }
25     return searchLasttarget(nums,length,start,end,target);
26 }
27 int search(int* nums, int numsSize, int target){
28     if(numsSize == 1 && nums[0] == target) return 1;
29     int firstTarget = searchFirsttarget(nums,numsSize,0,numsSize-1,target);
30     int lastTarget = searchLasttarget(nums,numsSize,0,numsSize-1,target);
31     if(firstTarget > -1 && lastTarget>-1)
32     return lastTarget - firstTarget + 1;
33     else return 0;
34 }
①找第一个值
②找第二个值

标签:end,target,nums,int,offer,53,middle,查找,start
来源: https://www.cnblogs.com/YoungP7/p/16124230.html