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

https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/

Medium

Given an array of integers nums 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].

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

  • 二分查找,需要理解对左右index上下界限如何设置。需要对左右index各做一次二分查找。
  • 查找左index时,如果遇到nums[middle] == target的情况,则还需要对左半边继续查找,因为要找到target第一次出现位置。
  • 查找右index时,选择查找target右边的第一个index,即target最后一次出现位置+1,所以在主程序里对返回结果-1。
  • https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/solution/ 
 1 class Solution:
 2     def searchRange(self, nums: List[int], target: int) -> List[int]:
 3         if nums is None:
 4             return [-1, -1]
 5         
 6         def helper(nums, target, search_left_index):
 7             left, right = 0, len(nums)
 8             
 9             while left < right:
10                 middle = (left + right) // 2
11                 
12                 # check if searching the leftmost index or not
13                 if nums[middle] > target or (search_left_index and nums[middle] == target):
14                     right = middle
15                 else:
16                     left = middle + 1
17             
18             return left
19         
20         left_index = helper(nums, target, True)
21         
22         if left_index == len(nums) or nums[left_index] != target:
23             return [-1, -1]
24         
25         return [ left_index, helper( nums, target, False ) - 1 ]
View Python Code

 

posted on 2019-08-27 21:58  浩然119  阅读(107)  评论(0编辑  收藏  举报