[leetcode]Search for a Range @ Python
2014-06-08 10:42
459 查看
原题地址:https://oj.leetcode.com/problems/search-for-a-range/
题意:
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
解题思路:又是二分查找的变形。因为题目要求的时间复杂度是O(log n)。在二分查找到元素时,需要向前和向后遍历来找到target元素的起点和终点。
代码:
题意:
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].
解题思路:又是二分查找的变形。因为题目要求的时间复杂度是O(log n)。在二分查找到元素时,需要向前和向后遍历来找到target元素的起点和终点。
代码:
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, A, target): left = 0; right = len(A) - 1 while left <= right: mid = (left + right) / 2 if A[mid] > target: right = mid - 1 elif A[mid] < target: left = mid + 1 else: list = [0, 0] if A[left] == target: list[0] = left if A[right] == target: list[1] = right for i in range(mid, right+1): if A[i] != target: list[1] = i - 1; break for i in range(mid, left-1, -1): if A[i] != target: list[0] = i + 1; break return list return [-1, -1]
相关文章推荐
- LeetCode 34 Search for a Range (C,C++,Java,Python)
- LeetCode- Search for a Range - Python
- LeetCode-34-Search for a Range Python实现lower_bound
- [LeetCode]题解(python):034-Search for a Range
- 【Leetcode】【python】Search for a Range
- leetcode Search for a Range python
- python实现 LeetCode34——Search for a Range
- [LeetCode]34. Search for a Range解法及python代码
- [LeetCode]Search for a Range@python
- python写算法题:leetcode: Add to List 34. Search for a Range
- LeetCode 34. Search for a Range (Python)
- LeetCode 34 — Search for a Range(C++ Java Python)
- python--leetcode34. Search for a Range
- LeetCode_Search for a Range
- [LeetCode]Search for a Range
- LeetCode - Search for a Range
- leetcode 96: Search for a Range
- LeetCode | Search for a Range
- Leetcode: Search for a Range
- LeetCode 38: Search for a Range