首页 > 其他 > 详细

34. Find First and Last Position of Element in Sorted Array

时间:2020-02-11 19:23:56      阅读:66      评论:0      收藏:0      [点我收藏+]
#用二分查找法
class
Solution(object): def searchRange(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ first = 0 last = len(nums) - 1 found = False results = [-1, -1] if nums == []: return results if target < nums[0] or target > nums[last]: return results while first <= last and not found: mid = (first + last) // 2 #找到了,分别继续向前,向后查找,直到找到第一个和最后一个target if target == nums[mid]: low = mid high = mid while low >= 0 and nums[low] == target: low -= 1 while high <= len(nums) - 1 and nums[high] == target: high += 1 found = True else: if target < nums[mid]: last = mid - 1 else: first = mid + 1 if found: return [low+1, high-1] else: return results

 

34. Find First and Last Position of Element in Sorted Array

原文:https://www.cnblogs.com/boluo007/p/12295796.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!