题目:统计一个数字在排序数组中出现的次数。

思路:采用二分查找,找到该数字在数组中第一次出现的位置,然后再找到组后一个出现的位置。两者做减法运算再加1.时间复杂度为O(logn)

Java代码:

//数字K在排序数组中出现的次数
//思路:用二分查找,找到第一个k和最后一个K
public class NumberCount {
public int numberCount(int[] a,int k){
if(a==null)
return 0;
int start=0;
int end=a.length-1;
int first=firstK(a,k,start,end);
int last=endK(a,k,start,end);
return last-first+1;
}
//通过二分查找,找到最后一个K
private int endK(int[] a, int k, int start, int end) {
if(a==null)
return 0;
int middle=(start+end)/2;
if(a[middle]==k){
if(a[middle]==k&&a[middle+1]!=k||middle==a.length-1)
return middle;
else
start=middle+1;
}
else if(a[middle]<k)
start=middle+1;
else
end=middle-1;
return endK(a,k,start,end);
}
//通过二分查找找到第一个K
public int firstK(int[] a, int k, int start, int end) {
if(a==null)
return 0;
int middle=(start+end)/2;
if(a[middle]==k){
if(middle==0||a[middle-1]!=k&&a[middle]==k)
return middle;
else
end=middle-1;
}
else if(a[middle]<k)
start=middle+1;
else
end=middle-1;
return firstK(a,k,start,end);
}
public static void main(String[] args) {
int[] a={1,3,3,3,7,4,5};
NumberCount numberCount=new NumberCount();
int number=numberCount.numberCount(a, 3);
System.out.println(number); }
}

最新文章

  1. [C++] C\C++ printf 输出格式
  2. Unity3D之ScriptableObject学习笔记
  3. linux环境下deb格式 转换成rpm格式
  4. Baidu Map Web API 案例
  5. eclipse设置web项目发布到tomcat根目录下
  6. 写一个程序,统计自己C语言共写了多少行代码,Github基本操作
  7. HTML5 开发APP( 支付宝支付)
  8. python汉字输出编码问题
  9. 自签名的https证书是不安全的
  10. 怎么用代码制作WordPress的归档页面
  11. vue2.0 带头冲锋(打包时,小心萝卜坑)
  12. [原创]..\OBJ\gpio.axf: error: L6002U: Could not open file ..\obj\gpio.o: No such file
  13. 补习系列(8)-springboot 单元测试之道
  14. ImageWatch 无法安装在VS2017环境下的解决方案
  15. linux环境下安装nginx步骤(不错)
  16. LOJ121 动态图连通性(LCT)
  17. Mysql8.0.11安装以及注意事项
  18. 2013成都网赛1003 hdu 4730 We Love MOE Girls
  19. ExpandoObject对象的JSON序列化
  20. pycharm的版本问题

热门文章

  1. ASP.NET MVC 处理404与500错误页面的方法
  2. jdbc封装代码
  3. ubuntu循环登录问题的解决
  4. 多线程-栅栏CyclicBarrier
  5. 嵌套的SQL另外一种写法
  6. hive 导出数据到本地
  7. 使用springmvc时报错HTTP Status 400 -
  8. legend---十二、js中的js语句和函数和ready函数的关系是什么
  9. python之单元测试框架—unittest(补充)
  10. Mac环境下Android Studio配置Git以及最基本使用