Given a sorted array of integers, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

思路:

我自己用了个最简单的,普通的二分查找,然后两边延伸找起始和结束点。

int *searchRange(int A[], int n, int target) {
int ans[] = {-, -};
int l = , r = n - ;
while(l <= r)
{
int m = (l + r) / ;
if(A[m] == target)
{
ans[] = ans[] = m;
while(ans[] - >= && A[ans[]] == A[ans[] - ]) ans[]--;
while(ans[] + < n && A[ans[]] == A[ans[] + ]) ans[]++;
return ans;
}
else if(A[m] > target)
r = m - ;
else
l = m + ;
}
return ans;
}

大神分成了分别用两次二分查找找起始和结束位置

https://leetcode.com/discuss/18242/clean-iterative-solution-binary-searches-with-explanation中有详细解释

vector<int> searchRange(int A[], int n, int target) {
int i = , j = n - ;
vector<int> ret(, -);
// Search for the left one
while (i < j)
{
int mid = (i + j) /;
if (A[mid] < target) i = mid + ;
else j = mid;
}
if (A[i]!=target) return ret;
else ret[] = i; // Search for the right one
j = n-; // We don't have to set i to 0 the second time.
while (i < j)
{
int mid = (i + j) / + ; // Make mid biased to the right
if (A[mid] > target) j = mid - ;
else i = mid; // So that this won't make the search range stuck.
}
ret[] = j;
return ret;
}

另一种通过加减0.5来找位置的方法

class Solution:
# @param A, a list of integers
# @param target, an integer to be searched
# @return a list of length 2, [index1, index2]
def searchRange(self, arr, target):
start = self.binary_search(arr, target-0.5)
if arr[start] != target:
return [-1, -1]
arr.append(0)
end = self.binary_search(arr, target+0.5)-1
return [start, end] def binary_search(self, arr, target):
start, end = 0, len(arr)-1
while start < end:
mid = (start+end)//2
if target < arr[mid]:
end = mid
else:
start = mid+1
return start

最新文章

  1. 四种比较简单的图像显著性区域特征提取方法原理及实现-----&gt; AC/HC/LC/FT。
  2. 到入百度LSS framework Reason: image not found
  3. JavaScript-navigator_userAgent-编写一段代码能够区分浏览器的主流和区分
  4. List Copy
  5. 电赛总结(四)&mdash;&mdash;波形发生芯片总结之AD9854
  6. FZU2165 v11(带权的重复覆盖)
  7. Cocos Studio1.5.0.1开发学习笔记(一)
  8. Android之Intent
  9. 无状态会话bean(3)---远程业务接口(没有排版)
  10. Java反射机制使用场景
  11. centos7设置静态IP地址
  12. shell脚本:通过域名获取证书的过期时间
  13. cJSON填坑记
  14. 关于ajax的controller层返回jsp页面多个list
  15. Blob下载文件 &amp; 模拟滚动条实现
  16. SQLDumpSplitter sql文件分割工具
  17. react-native 相关问题
  18. opencv3.2.0图像处理之中值滤波medianBlur API函数
  19. 2017-2018-1 20155230 mypwd实现
  20. Python 利用 BeautifulSoup 爬取网站获取新闻流

热门文章

  1. nyoj 613 免费馅饼 广搜
  2. SharePoint Server 2010 中的基本任务
  3. javacomm64位用不了,可以使用RXTXcomm for x64
  4. FLAG是什么公司
  5. 【PHP面向对象(OOP)编程入门教程】1.什么是面向对象?
  6. HomeWork2
  7. Windbg学习使用
  8. 开发板支持wifi
  9. Windows下几个常用的和进程有关的命令
  10. 分享一个c#t的网页抓取类