Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 81 · Rotated Sorted Array

Search in Rotated Sorted Array II

LeetCode 81 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

nums[low] == nums[mid] == nums[high] ⇒ low++, high−−.

நடுத்தரம்ArrayBinary Search
LeetCode இல் திற ↗

நான் Search in Rotated Sorted Array II (LeetCode 81) ஐ இப்படித் தீர்த்தேன் — Rotated Sorted Array பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.

கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.

Intuition

Like the distinct version, but duplicates can hide which half is sorted (e.g. low, mid and high all equal). In that ambiguous case shrink both ends by one and retry.

Approach

  1. 1

    mid matches → True.

  2. 2

    Ambiguous triple → shrink both ends.

  3. 3

    Otherwise apply the sorted-half test.

  4. 4

    Not found → False.

நான் எப்படித் தீர்த்தேன்

Binary search with duplicate shrinkPythonO(log n) avg
class Solution:
    def search(self, nums: List[int], target: int) -> bool:
        low = 0
        high=len(nums)-1
        while low<=high:
            mid = (low+high)//2
            if nums[mid]==target:
                return True
            if nums[low]==nums[mid] and nums[mid]==nums[high]:
                low = low+1
                high= high-1
                continue
            if nums[low]<=nums[mid]:
                #left half is sorted
                if target>=nums[low] and target<nums[mid]:
                    high = mid-1
                else:
                    low=mid+1
            else:
                if target>nums[mid] and target<=nums[high]:
                    low=mid+1
                else:
                    high=mid-1
        return False
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Search in Rotated Sorted Array II — அடிக்கடி கேட்கப்படும் கேள்விகள்

Search in Rotated Sorted Array II பின்னாலுள்ள intuition என்ன?

Like the distinct version, but duplicates can hide which half is sorted (e.g. low, mid and high all equal). In that ambiguous case shrink both ends by one and retry.

Search in Rotated Sorted Array II (LeetCode 81) ஐ எப்படித் தீர்ப்பது?

1. mid matches → True. 2. Ambiguous triple → shrink both ends. 3. Otherwise apply the sorted-half test. 4. Not found → False.

Search in Rotated Sorted Array II இன் time மற்றும் space complexity என்ன?

Time: O(log n) average, O(n) worst. Space: O(1). (Accepted approach: Binary search with duplicate shrink.)

Search in Rotated Sorted Array II இல் பொதுவான தவறுகள் என்ன?

Duplicates make the worst case linear — that's unavoidable.