leetcode之-题34
2016-05-01 22:33
302 查看
题目
Search for a RangeGiven 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].
题解
想必大家看到时间要求O(log n),已经想到了需要使用二分查找,二分查找很简单,关键是这个题目要我们找到
target的区间
其实很简单,分成两步就好了,第一次尽量向左走,第二次尽量向右走,获得左边和右边的位置,返回即可
(1)寻找最左的index: 找到相等时,
high=mid,让它一直向左走
(2)寻找最右的index: 找到相等时,
low=mid,让它一直向右走
代码
#!/usr/bin/python # -*- coding:utf-8 -*- class Solution(object): def searchRange(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ if len(nums) == 0: return [-1, -1] start_index = self.lsearch(nums, target) end_index = self.rsearch(nums, target) return [start_index, end_index] def rsearch(self, nums, target): # 二分查找,相等时候一直向右 low = 0 high = len(nums) - 1 while low < high - 1: mid_index = (low + high) // 2 if nums[mid_index] > target: high = mid_index - 1 elif nums[mid_index] < target: low = mid_index + 1 else: low = mid_index if nums[high] == target: return high elif nums[low] == target: return low else: return -1 def lsearch(self, nums, target): # 二分查找,一直向左走 low = 0 high = len(nums) - 1 while low < high - 1: mid_index = (low + high) // 2 if nums[mid_index] > target: high = mid_index - 1 elif nums[mid_index] < target: low = mid_index + 1 else: high = mid_index if nums[low] == target: return low elif nums[high] == target: return high else: return -1 if __name__ == '__main__': a = Solution() st = a.searchRange([1,8,8,8,8,9,9,10,10,10,11], 8) print st
相关文章推荐
- iOS之tableView(五)的编辑删除插入操作和UIAlertController的使用
- STL算法_heap算法篇
- Android面试题——Java面向对象思想
- Problem E: 输入两个整数,进行四则运算并输出结果
- ubuntu 安装 jdk+myeclipse
- splite3 简单2片
- MapReduce Intro
- MIT 6.828 学习笔记4 Lab2实验报告
- javascript实现n阶乘的2个方法
- 网球训练
- opencv文件读写(二)使用多种方式及用法
- 成功在家用ssh远程连上了学校电脑虚拟机当中的ubuntu(代价是虚拟机全部黑屏只能用SSH连接了!)
- iOS之短信,邮件,通信录技术的完美实现
- Vb生成一定范围内的随机数(含小数部分)
- python zip 生成字典
- 合并k个有序链表
- mac 多版本jdk并存解决方案
- 一元多项式的乘法与加法运算 PTA02-线性结构1
- hdu 5667 Sequence 矩阵快速幂
- windows7下emacs安装