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/css

Medium

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.ide

Your algorithm's runtime complexity must be in the order of O(log n).spa

If the target is not found in the array, return [-1, -1].3d

Example 1:code

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

Example 2:blog

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

  • 二分查找,須要理解對左右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
相關文章
相關標籤/搜索