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

转载自Leet Code《剑指Offer》

题目描述

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

示例 1

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

示例 2

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

提示:

  • 0 <= nums.length <= 105
  • -109 <= nums[i] <= 109
  • nums是一个非递减数组
  • -109 <= target <= 109

我的代码

{.line-numbers}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class MySolutionOffer53I {
public int search(int[] nums, int target) {

int count = 0;
if (nums==null||nums.length==0) return count;

int index0 = BinarySearch(nums, 0, nums.length, target);
if (index0>=nums.length||nums[index0]!=target) return count;

int index1 = BinarySearch(nums,index0,nums.length,target+1);
return index1-index0;
}

// array[first, last); array[index]>=value
static int BinarySearch(int []array, int first, int last, int value)
{
while (first<last)
{
int mid = first+(last-first)/2;
if (array[mid]<value)
first = mid+1;
else
last=mid;
}
return first; //or last.
}
}