Remove Duplicates from Sorted Array II
LeetCode 80 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Keep nums[i] unless it equals nums[insert_index − 2].
నేను Remove Duplicates from Sorted Array II (LeetCode 80) ను ఇలా పరిష్కరించాను — Two Pointers ప్యాటర్న్లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
Allow each value at most twice: compare the incoming element with the one two slots behind the write position. If they're equal, a third copy would appear, so skip it.
Approach
- 1
The first two elements are always kept; insert_index = 2.
- 2
For each later element, skip it if it matches nums[insert_index − 2].
- 3
Otherwise write it and advance.
- 4
Return insert_index.
నేను ఎలా పరిష్కరించాను
Write pointer, look back twoPythonO(n) time · O(1) space
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
insert_index=2
for i in range(2,len(nums)):
if nums[i]==nums[insert_index-2]:
continue
nums[insert_index]=nums[i]
insert_index+=1
return insert_indexRemove Duplicates from Sorted Array II — తరచూ అడిగే ప్రశ్నలు
Remove Duplicates from Sorted Array II వెనుక ఉన్న intuition ఏమిటి?
Allow each value at most twice: compare the incoming element with the one two slots behind the write position. If they're equal, a third copy would appear, so skip it.
Remove Duplicates from Sorted Array II (LeetCode 80) ను ఎలా పరిష్కరించాలి?
1. The first two elements are always kept; insert_index = 2. 2. For each later element, skip it if it matches nums[insert_index − 2]. 3. Otherwise write it and advance. 4. Return insert_index.
Remove Duplicates from Sorted Array II యొక్క time, space complexity ఎంత?
Time: O(n). Space: O(1). (Accepted approach: Write pointer, look back two.)
Remove Duplicates from Sorted Array II లో సాధారణ పొరపాట్లు ఏమిటి?
Compare against the write area, not the read area — that's what limits copies to two.