Leetcode 34. Find the first and last positions of elements in sorted array | Python

Time:2021-2-26

34. Find the first and last positions of the elements in the sorted array


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

subject


Given an integer array nums in ascending order and a target value target. Find out the start and end position of the given target value in the array.

Your algorithm time complexity must be o (log n) level.

If there is no target value 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]

Thinking of solving problems


Idea: binary search

The time complexity of the algorithm must beO(log n)And it means that the given array has been arranged in ascending order. So here, we consider using binary search to solve this problem.

Here, if there are no above restrictions, we can use linear time to solve the problem.

Specific implementation process:

  • First, traverse the array from left to right. When the first element is the same as the target value, record the index and jump out of the loop. If there is no element with the same target value at the end of the loop, return it directly[-1, -1]
  • The second traversal, from right to left traversal, also encountered the first andtargetFor elements with equal values, the record index exits the loop.
  • Finally, two index values are returned.

The above is the solution of linear time without limiting the time complexity. It is suggested that you can try to write the code, which will not be posted here.

The following is mainly about how to use binary search to solve problems.

The index of the leftmost and rightmost corresponding values is also searched twice. It should be noted here that no matter you are looking for the leftmost or rightmost element index, you are not looking for andtargetThe index of elements with the same value will stop immediately, because the elements will repeat, and the first element found may not be the leftmost or rightmost element.

What we need to pay attention to here is that when we look up the left and right elements, we need to pay attention to the boundary problem. Here we use and short circuit calculation to introduce a variablesignTo deal with boundary problems.

When the element value is the same as the target value, ifsignWhen true, the left part should be searched at this time. If the current element value is equal to target, the index of the leftmost element cannot be larger than the current element index, so the range should be narrowed to the left part. Similarly, the right index is the same.

The specific code implementation is as follows.

code implementation


class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        def search_index(nums, target, sign):
            left = 0
            right = len(nums)

            while left < right:
                mid = (left+right) // 2
                if nums[mid] > target or (sign and target==nums[mid]):
                    right = mid
                else:
                    left = mid + 1
        
            return left

        left_index = search_index(nums, target, True)

        #Here, judge in advance whether the retrieved index has reached the end
        #Or whether the corresponding value of the retrieved index is not target,
        #If it is the above two cases, return [- 1, - 1]
        if left_index == len(nums) or nums[left_index] != target:
            return [-1, -1]

        right_index = search_index(nums, target, False) - 1
        return [left_index, right_index]

Implementation results


Leetcode 34. Find the first and last positions of elements in sorted array | Python

Recommended Today

C # regular implementation of UBB parsing class code

The parsed code can pass XHTML   one   Strict verification;It includes title, link, font, alignment, picture, reference, list and other functions  Ubb.ReadMe.htm UBB code description title [H1] title I [/ H1] Title I [H2] Title II [/ H2] Title II [H1] Title III [/ H1] Title III [H4] Title IV [/ H4] Title IV […]