跳转至

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

限制:

0 <= 数组长度 <= 50000

注意:本题与主站 34 题相同(仅返回值不同):https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/

题解

class Solution {
    //思路:先二分查找只好到索引
   //然后索引向前向后遍历相同的值 累加
    public int search(int[] nums, int target) {
        if(nums == null || nums.length == 0) return 0;
        int i = Arrays.binarySearch(nums,target);
        if(i<0) return 0;
        int j = i - 1;
        int k = i + 1;
        int count = 1;
        while(j >=0&&nums[i]==nums[j]){
           count++;
           j--;
        }
        while(k<nums.length&&nums[i]==nums[k]){
            count++;
            k++;
        }
        return count;
    }
}