Java教程

剑指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 }
①找第一个值
②找第二个值
③
这篇关于剑指offer_53 在排序数组中查找数字 I的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!