Remove Element
LeetCode 27 · எளிது · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
Keep-if-not-val with a write index.
நான் Remove Element (LeetCode 27) ஐ இப்படித் தீர்த்தேன் — Two Pointers பேட்டர்னின் ஒரு எளிது பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.
கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.
Intuition
Scan once and copy every element that isn't val to the next write position. Whatever is left past the write index doesn't matter.
Approach
- 1
insert_index = 0.
- 2
For each num ≠ val, write it at insert_index and advance.
- 3
Return insert_index.
நான் எப்படித் தீர்த்தேன்
Write pointerPythonO(n) time · O(1) space
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
insert_index=0
for num in nums:
if num!=val:
nums[insert_index]=num
insert_index+=1
return insert_indexRemove Element — அடிக்கடி கேட்கப்படும் கேள்விகள்
Remove Element பின்னாலுள்ள intuition என்ன?
Scan once and copy every element that isn't val to the next write position. Whatever is left past the write index doesn't matter.
Remove Element (LeetCode 27) ஐ எப்படித் தீர்ப்பது?
1. insert_index = 0. 2. For each num ≠ val, write it at insert_index and advance. 3. Return insert_index.
Remove Element இன் time மற்றும் space complexity என்ன?
Time: O(n). Space: O(1). (Accepted approach: Write pointer.)
Remove Element இல் பொதுவான தவறுகள் என்ன?
Order beyond the first k elements is irrelevant.