当前位置: 代码迷 >> 综合 >> Java统计一个数字在排序数组中出现的次数
  详细解决方案

Java统计一个数字在排序数组中出现的次数

热度:71   发布时间:2024-02-01 12:04:50.0

题目描述

统计一个数字在排序数组中出现的次数

public class Solution {public int GetNumberOfK(int [] array , int k) {int start = twoFenLeft(array,k);int tail = twoFenRight(array,k);if(start == -1 || tail == -1){return 0;}return  tail-start+1;}//二分查找左边界public int twoFenLeft(int[] a,int target){int low = 0;int high = a.length-1;while(low <= high){int mid = low + (high - low)/2;if(a[mid] == target){high = mid - 1;}else if(a[mid] > target){high = mid - 1;}else{low = mid + 1;}}// 最后要检查 left 越界的情况if(low>=a.length || target!=a[low]){return -1;}return low;}//二分查找右边界public int twoFenRight(int[] a,int target){int low = 0;int high = a.length-1;            while(low <= high){int mid = low + (high - low)/2;if(a[mid] == target){low = mid + 1;}else if(a[mid] > target){high = mid - 1;}else{low = mid + 1;}}// 最后要检查 right 越界的情况if(high<0 || target!=a[high]){return -1;}return high;}
}