0
点赞
收藏
分享

微信扫一扫

【Kevin Learn 算法与数据结构】-->《剑指 offer》数字在排序数组中出现的次数

题目描述

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

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;
}
}

测试结果

【Kevin Learn 算法与数据结构】-->《剑指 offer》数字在排序数组中出现的次数_牛客网


举报

相关推荐

0 条评论