package org.example.test; /** * 先用二分查找比K大一的数,然后在向后遍历求总数,直到不等于K为止 */ public class GetNumberOfKTest { public static void main(String[] args) { int[] test = {1, 2, 3, 3, 3, 3, 4, 5}; System.out.println(GetNumberOfK(test, 3)); } public static int GetNumberOfK(int[] array, int k) { int left = 0; int right = array.length - 1; int ans = 0; while (left <= right) { int mid = (left + right) / 2; if (array[mid] > k + 1) { right = mid - 1; } else if (array[mid] == k + 1) { right = mid - 1; } else if (array[mid] < k + 1) { left = mid + 1; } } for (int i = left - 1; i >= 0; i--) { if (array[i] != k) { break; } ans++; } return ans; } }