Check if Array Is Sorted and Rotated
LeetCode 1752 · எளிது · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
Count descents including the wrap-around; ≤ 1 means yes.
நான் Check if Array Is Sorted and Rotated (LeetCode 1752) ஐ இப்படித் தீர்த்தேன் — Linear Scan பேட்டர்னின் ஒரு எளிது பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.
கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.
Intuition
A sorted array rotated any amount has at most one 'drop' where a value is bigger than the next one, counting the wrap from the last element back to the first. More than one drop means it can't be a rotation of a sorted array.
Approach
- 1
Count positions where nums[i−1] > nums[i].
- 2
Also count the wrap if nums[n−1] > nums[0].
- 3
Return count ≤ 1.
நான் எப்படித் தீர்த்தேன்
Count descentsPythonO(n) time · O(1) space
class Solution:
def check(self, nums):
count = 0
n = len(nums)
for i in range(1, n):
if nums[i - 1] > nums[i]:
count += 1
if nums[n - 1] > nums[0]:
count += 1
if count <= 1:
return True
return FalseCheck if Array Is Sorted and Rotated — அடிக்கடி கேட்கப்படும் கேள்விகள்
Check if Array Is Sorted and Rotated பின்னாலுள்ள intuition என்ன?
A sorted array rotated any amount has at most one 'drop' where a value is bigger than the next one, counting the wrap from the last element back to the first. More than one drop means it can't be a rotation of a sorted array.
Check if Array Is Sorted and Rotated (LeetCode 1752) ஐ எப்படித் தீர்ப்பது?
1. Count positions where nums[i−1] > nums[i]. 2. Also count the wrap if nums[n−1] > nums[0]. 3. Return count ≤ 1.
Check if Array Is Sorted and Rotated இன் time மற்றும் space complexity என்ன?
Time: O(n). Space: O(1). (Accepted approach: Count descents.)
Check if Array Is Sorted and Rotated இல் பொதுவான தவறுகள் என்ன?
Equal neighbours are not drops.