Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 34 · Basics / Lower & Upper Bound

Find First and Last Position of Element in Sorted Array

LeetCode 34 · मध्यम · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

Two biased binary searches.

मध्यमArrayBinary Search

मी Find First and Last Position of Element in Sorted Array (LeetCode 34) असा सोडवला — Basics / Lower & Upper Bound पॅटर्नमधील एक मध्यम प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि line-by-line debugger.

खालील विवरण इंग्रजीत आहे.

Intuition

Run binary search twice. When you hit the target, don't stop: record it and keep searching left for the first position, or right for the last position.

Approach

  1. 1

    First: on a match, save mid and set high = mid − 1.

  2. 2

    Last: on a match, save mid and set low = mid + 1.

  3. 3

    Return [first, last] (−1 if absent).

मी कसा सोडवला

Lower + upper bound searchesPythonO(log n) time
class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        def getFirstPosition():
            ans=-1
            low = 0
            high=len(nums)-1
            while low<=high:
                mid = (low+high)//2
                if nums[mid]==target:
                    ans = mid
                    high = mid-1
                elif nums[mid]>target:
                    high = mid-1
                else:
                    low = mid+1
            return ans
        def getLastPosition():
            ans=-1
            low = 0
            high=len(nums)-1
            while low<=high:
                mid = (low+high)//2
                if nums[mid]==target:
                    ans = mid
                    low = mid+1
                elif nums[mid]>target:
                    high = mid-1
                else:
                    low = mid+1
            return ans
        first = getFirstPosition()
        last = getLastPosition()
        return [first,last]
स्टेप-थ्रू लोड होत आहे…

Find First and Last Position of Element in Sorted Array — वारंवार विचारले जाणारे प्रश्न

Find First and Last Position of Element in Sorted Array मागील intuition काय आहे?

Run binary search twice. When you hit the target, don't stop: record it and keep searching left for the first position, or right for the last position.

Find First and Last Position of Element in Sorted Array (LeetCode 34) कसा सोडवावा?

1. First: on a match, save mid and set high = mid − 1. 2. Last: on a match, save mid and set low = mid + 1. 3. Return [first, last] (−1 if absent).

Find First and Last Position of Element in Sorted Array ची time आणि space complexity किती आहे?

Time: O(log n). Space: O(1). (Accepted approach: Lower + upper bound searches.)

Find First and Last Position of Element in Sorted Array मध्ये सामान्य चुका कोणत्या?

A linear scan from one hit is O(n) in the worst case.