import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @param k int整型 * @return int整型 */ public int GetNumberOfK (int[] nums, int k) { // write code here if (nums == null){ return 0; } int ret = 0; int left = 0; int right = nums.length - 1; int mid = (left + right) / 2; while(left <= right){ if (nums[mid] < k){ left = mid + 1; }else if (nums[mid] > k){ right = mid - 1; }else{ ret++; int[] a = new int[2]; for (int i = 1; i < nums.length; i++){ if (mid + i < nums.length){ if (nums[mid+i] == k){ ret++; }else{ a[0] = 1; } } if (mid - i >= 0){ if (nums[mid-i] == k){ ret++; }else{ a[1] = 1; } } if (a[0] == 1 && a[1] == 1){ return ret; } } break; } mid = (left + right) / 2; } return ret; } }