【算法求一个数字在给定的已排序数组中出现的起始终止索引号】贵有恒,何必三更起、五更眠、最无益,只怕一日曝、十日寒。这篇文章主要讲述算法求一个数字在给定的已排序数组中出现的起始终止索引号相关的知识,希望能为你提供帮助。
方法一
public class findthefirstandlast
public int finderfirstandlast(int[] arr, int target)
int first = findfirstindex(arr, target);
int last = findlastindex(arr, target);
System.out.println(first);
System.out.println(last);
return findlastindex(arr, target) - findfirstindex(arr, target);
public int findfirstindex(int[] arr, int target)
int left = 0;
int right = arr.length - 1;
int mid;
while (left < = right)
mid = (left + right) / 2;
if (arr[mid] < target)
left = mid + 1;
else if (arr[mid] > target)
right = mid - 1;
else
if ( mid == 0 || arr[mid - 1] != target)
return mid;
right = mid - 1;
return -1;
public int findlastindex(int[] arr, int target)
int left = 0;
int right = arr.length - 1;
int mid;
while (left < = right)
mid = (left + right) / 2;
if (arr[mid] < target)
left = mid + 1;
else if (arr[mid] > target)
right = mid - 1;
else
if (mid == arr.length - 1 || arr[mid + 1] != target)
return mid;
left = mid + 1;
return -1;
?
参考链接http://www.mamicode.com/info-detail-184617.html
推荐阅读
- shell``和$()作用与区别
- JAVASession
- seleniumselenium find_element()详解
- Git入门第二讲(创建版本库)
- --PostgreSQL怎么正确的开始POSTGRESQL 调优的活动1
- PostgreSQL读书会一期系统目录表1
- Redis哪些地方需要调整 杂谈
- PostgreSQL“千万” 不能做五大 foolish 操作
- 防火墙基础之安全策略和GRE隧道