Search in Rotated Sorted Array II
LeetCode 81 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
nums[low] == nums[mid] == nums[high] ⇒ low++, high−−.
ನಾನು 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
mid matches → True.
- 2
Ambiguous triple → shrink both ends.
- 3
Otherwise apply the sorted-half test.
- 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 FalseSearch 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.