【LeetCode题意分析&解答】34. Search for a Range
2016-03-12 23:32
501 查看
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
For example,
Given
return
题意分析:
本题是在一个递增数组中查找目标值target下标的边界,可以得到两个信息:1.数组会有重复值;2.数组是严格单调递增的。
解答:
本题要求时间复杂度是 O(log n),提示我们可以用二分查找去做(注意不能先用二分查找找到target,然后向两侧寻找边界,这种方法是不符合时间复杂度要求的)。既然是一个范围,那么我们可以查找两次,分别把两个边界找出来。这里我是先查找到左边界,然后将左边界后面的数组作为新的数组查找右边界。这和二分查找的思想一致,但是需要注意迭代的条件是不同的。
AC代码:
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].
题意分析:
本题是在一个递增数组中查找目标值target下标的边界,可以得到两个信息:1.数组会有重复值;2.数组是严格单调递增的。
解答:
本题要求时间复杂度是 O(log n),提示我们可以用二分查找去做(注意不能先用二分查找找到target,然后向两侧寻找边界,这种方法是不符合时间复杂度要求的)。既然是一个范围,那么我们可以查找两次,分别把两个边界找出来。这里我是先查找到左边界,然后将左边界后面的数组作为新的数组查找右边界。这和二分查找的思想一致,但是需要注意迭代的条件是不同的。
AC代码:
class Solution(object): def searchRange(self, nums, target): left = 0 right = r_right = len(nums) - 1 # find the left of range while left < right: mid = (left + right) / 2 if nums[mid] < target: left = mid + 1 else: right = mid # can't find target if nums[left] != target: return [-1, -1] while right < r_right: # notice: mid should be close to right mid = (right + r_right) / 2 + 1 if nums[mid] > target: r_right = mid - 1 else: right = mid return [left, right]
相关文章推荐
- Spring学习笔记--环境搭建和初步理解IOC
- Scala学习笔记--第3章 函数
- 堆排序 两种实现(最小堆和最大堆)
- 复利计算1.0,2.0
- Git Feature分支
- 集成hbase
- 《第一行代码》 随手笔记——第三章 UI开发的点点滴滴
- oracle创建表空间
- 配置mysql允许远程连接的方法
- UITableView介绍 之 复杂cell的高度计算
- 1016-06-首页20-封装工具条---UITableView控件距离顶部的间距问题----cell选中时的背景颜色设置
- Servlet+msql+ android客户端实现从服务器获取信息
- 第三周上机实践项目——项目4-穷举法解决组合问题
- 目前流行的源程序版本管理软件和项目管理软件都有哪些?各有什么优缺点?
- Git Bug分支
- Device eth1 does not seem to be present, delaying initialization.
- 指针运算
- 机器学习常用算法总结
- AOP + 动态代理 + Proxy模式
- MySql优化【6】--压力测试脚本