《剑指 offer》 学习37之数字在排序数组中出现的次数

题目描述

统计一个数字在排序数组中出现的次数。
题目链接:牛客网

Input:
nums = 1, 2, 3, 3, 3, 3, 4, 6
K = 3

Output:
4

解题思路


public class Main {
    
	public static void main(String[] args) {
		int[] nums = {1, 2, 3, 3, 3, 3, 4, 6};
		
		System.out.println(getNumberOfK(nums,3));
	}
	
	public static int getNumberOfK(int[] array , int k) {
        int first = binarySearch(array,k);
        int last = binarySearch(array,k + 1);
        
        return (first == array.length || array[first] != k) ? 0 : last - first;
    }
    
    public static int binarySearch(int[] nums,int k) {
        int l = 0;
        int h = nums.length;
        while (l < h) {
            int m = l + (h - l) / 2;
            if (nums[m] >= k) {
                h = m;
            } else {
                l = m + 1;
            }
        }
        
        return l;
    }
}

测试结果

image.png

猜你喜欢

转载自blog.csdn.net/duoduo_11011/article/details/107753663