标签:
题目来源
https://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 [-1, -1]
.
题意分析
Input: a list and a target(int)
Output: a list with the first index and the last index of target in the input list
Conditions:时间复杂度为0(logn),两个index分别为起始和最后位置
题目思路
本题可采用二分查找的算法,复杂度是0(logn),首先通过二分查找找到taregt出现的某一个位置,然后以这个位置,以及此时的(first,last)来二分查找最左出现的位置和最右出现的位置
PS:注意边界条件
AC代码(Python)
1 _author_ = "YE" 2 # -*- coding:utf-8 -*- 3 class Solution(object): 4 def findRight(self, nums, first, mid): 5 if nums[first] == nums[mid]: 6 return mid 7 nmid = (first + mid) // 2 8 if nmid == first: 9 return first 10 if nums[nmid] == nums[first]: 11 return self.findRight(nums, nmid, mid) 12 else: 13 return self.findRight(nums,first, nmid) 14 15 def findLeft(self, nums, mid, last): 16 if nums[mid] == nums[last]: 17 return mid 18 nmid = (mid + last) // 2 19 if nmid == mid: 20 return last 21 if nums[nmid] == nums[last]: 22 return self.findLeft(nums, mid, nmid) 23 else: 24 return self.findLeft(nums,nmid + 1, last) 25 26 27 def searchRange(self, nums, target): 28 """ 29 :type nums: List[int] 30 :type target: int 31 :rtype: List[int] 32 """ 33 last = len(nums) 34 first = 0 35 while first < last: 36 mid = (first + last) // 2 37 # print(first,mid,last) 38 if nums[mid] == target: 39 # print(self.findLeft(nums,first, mid)) 40 # print(self.findRight(nums,mid,last - 1)) 41 return [self.findLeft(nums,first, mid), self.findRight(nums,mid,last - 1)] 42 elif nums[mid] < target: 43 first = mid + 1 44 else: 45 last = mid 46 47 return [-1,-1]
[LeetCode]题解(python):034-Search for a Range
标签:
原文地址:http://www.cnblogs.com/loadofleaf/p/5004525.html