您的位置:首页 > 其它

leetcode: 34. Search for a Range

2017-11-11 17:21 357 查看

Problem

# Given an array of integers sorted in ascending order, 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].


AC

class Solution():
def searchRange(self, x, target):
import bisect
l, r = bisect.bisect_left(x, target), bisect.bisect_right(x, target)
l = -1 if l >= len(x) or x[l] != target else l
r = -1 if r == 0 or x[r - 1] != target else r - 1
return [l, r]

if __name__ == "__main__":
assert Solution().searchRange([2, 2], 3) == [-1, -1]
assert Solution().searchRange([5, 7, 7, 8, 8, 10], 8) == [3, 4]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: