统计一个数字在排序数组中出现的次数
2020-05-03 19:39
87 查看
//统计一个数字在排序数组中出现的次数 //排序数组{1,2,3,4,5,5,5,6,7,8,10,12}和 数字5 import java.util.Arrays; public class SumNumArray { public static int getFirstkey(int[] arr,int key){ int low=0; int high=arr.length-1; int mid=0; while(low<=high){ mid = (low+high)/2; if (arr[mid]==key){ if(arr[mid-1]!=key||mid==0){ return mid; }else { high=mid-1; } }else if(arr[mid]>key){ high=mid-1; }else { low=mid+1; } } return -1; } public static int getLastkey(int[] arr,int key){ int low=0; int high=arr.length-1; int mid=0; while(low<=high){ mid = (low+high)/2; if (arr[mid]==key){ if(arr[mid+1]!=key||mid==arr.length-1){ return mid; }else { low=mid+1; } }else if(arr[mid]<key){ low=mid+1; }else { high=mid-1; } } return -1; } public static int Sum(int []arr,int key){ int count=0; count = getLastkey(arr,key)-getFirstkey(arr,key)+1; return count; } public static void main(String[] args){ int []arr = {1,2,3,4,4,4,4,4,4,4,4,4,4,5,5,5,6,7,8,10,12}; System.out.println(Sum(arr,4)); } }
相关文章推荐
- 一个一维整形数组,若干个数字,统计数组中不同的数字出现的次数,并按照出现频率从小到大排序输出,相同频率按数字大小排序输出
- 【c语言】统计一个数字在排序数组中出现的次数
- 【剑指Offer-知识迁移能力】统计一个数字在排序数组中出现的次数。
- 统计一个数字在排序数组中出现的次数(二分法)
- (4)统计一个数字,在排序数组中出现的次数
- 统计一个数字在排序数组中出现的次数。 数组是排序的,只需要找到第一个K和最后一个K就可以知道有多少个,
- 统计一个数字在排序数组中出现的次数(二分法)
- 统计一个数字在排序数组中出现的次数(二分法)
- 《牛客网剑指offer37题》统计一个数字在排序数组中出现的次数
- 统计一个数字在排序数组中出现的次数
- 统计一个数字在排序数组中出现的次数
- 牛客--统计一个数字在排序数组中出现的次数
- 剑指offer-统计一个数字在排序数组中出现的次数
- 剑指offer-统计一个数字在排序数组中出现的次数-PHP
- 统计一个数字在排序数组中出现的次数
- 剑指Offer:统计一个数字在排序数组中出现的次数。(java)
- 统计一个数字在排序数组中出现的次数
- 统计一个数字在排序数组中出现的次数
- 统计一个数字在排序数组中出现的次数
- 统计一个数字在排序数组(从小到大排序)中出现的次数。