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

Posted pegasus923

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

 

以上是关于Leetcode 34. Find First and Last Position of Element in Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 34. Search for a Range 搜索一个范围(Find First and Last Position of Element in Sorted Array)(代码

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

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

[leetcode][34] Find First and Last Position of Element in Sorted Array

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

[二分搜索] leetcode 34 Find First and Last Position of Element in Sorted Array