Find First and Last Position of Element in Sorted Array
LeetCode 34 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
Two biased binary searches.
நான் 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
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).
நான் எப்படித் தீர்த்தேன்
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.