Find Minimum in Rotated Sorted Array II
LeetCode 154 · కఠినం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Equal ⇒ high −= 1.
నేను Find Minimum in Rotated Sorted Array II (LeetCode 154) ను ఇలా పరిష్కరించాను — Rotated Sorted Array ప్యాటర్న్లోని ఒక కఠినం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
Same comparison with the right end, plus one case for duplicates: when nums[mid] equals nums[high] you can't tell which side holds the minimum, but you can safely drop high because mid has the same value.
Approach
- 1
nums[mid] > nums[high] → minimum is right: low = mid + 1.
- 2
nums[mid] < nums[high] → high = mid.
- 3
Equal → high −= 1.
- 4
Return nums[low].
నేను ఎలా పరిష్కరించాను
Binary search with duplicatesPythonO(log n) avg
class Solution:
def findMin(self, nums: List[int]) -> int:
low = 0
high= len(nums)-1
while low<high:
mid = (low+high)//2
#2,2,2,0,1 if nums[mid]>nums[high],smallest will be on the right half
if nums[mid]>nums[high]:
low = mid+1
#1,3,5 if nums[mid]<nums[high], the lowest must be on the left half, include mid 3,1,3 to handle this special case to include mid as well
elif nums[mid]<nums[high]:
high = mid
#10,1,10,10 reduce the search space if nums[mid] and nums[high] are equal
else:
high = high-1
return nums[low]Find Minimum in Rotated Sorted Array II — తరచూ అడిగే ప్రశ్నలు
Find Minimum in Rotated Sorted Array II వెనుక ఉన్న intuition ఏమిటి?
Same comparison with the right end, plus one case for duplicates: when nums[mid] equals nums[high] you can't tell which side holds the minimum, but you can safely drop high because mid has the same value.
Find Minimum in Rotated Sorted Array II (LeetCode 154) ను ఎలా పరిష్కరించాలి?
1. nums[mid] > nums[high] → minimum is right: low = mid + 1. 2. nums[mid] < nums[high] → high = mid. 3. Equal → high −= 1. 4. Return nums[low].
Find Minimum in Rotated Sorted Array II యొక్క time, space complexity ఎంత?
Time: O(log n) average, O(n) worst. Space: O(1). (Accepted approach: Binary search with duplicates.)
Find Minimum in Rotated Sorted Array II లో సాధారణ పొరపాట్లు ఏమిటి?
Don't jump high = mid on equality — the minimum could be between.