标签:
题目来源:
https://leetcode.com/problems/search-for-a-range/
题意分析:
给定一个有序数组,和一个target。返回这个target的最左和最右位置,如果没有找到返回[-1,-1]。解题的时间复杂度要求是log(n)。
题目思路:
这里分3步二分查找,第一个二分查到找到target的任意位置,第二个二分查找找到最左的位置,第三个是二分找到最右的位置。
代码(python):
1 class Solution(object): 2 def findLeft(self,nums,first,mid): 3 if nums[first] == nums[mid]: 4 return first 5 nmid = (first + mid) // 2 6 if nums[nmid] == nums[mid]: 7 return self.findLeft(nums,first,nmid) 8 return self.findLeft(nums,nmid + 1,mid) 9 def findRight(self,nums,mid,last): 10 if nums[last] == nums[mid]: 11 return last 12 nmid = (mid + last + 1) // 2 13 if nums[nmid] == nums[mid]: 14 return self.findRight(nums,nmid,last) 15 return self.findRight(nums,mid,nmid - 1) 16 def searchRange(self, nums, target): 17 """ 18 :type nums: List[int] 19 :type target: int 20 :rtype: List[int] 21 """ 22 last = len(nums);first = 0 23 while first != last: 24 mid = (first + last) // 2 25 if nums[mid] == target: 26 return [self.findLeft(nums,first,mid),self.findRight(nums,mid,last - 1)] 27 elif nums[mid] < target: 28 first = mid + 1 29 else: 30 last = mid 31 return [-1,-1] 32
转载请注明出处:http://www.cnblogs.com/chruny/p/4918421.html
[LeetCode]题解(python):034-Search for a Range
标签:
原文地址:http://www.cnblogs.com/chruny/p/4918421.html