Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 80 · Two Pointers

Remove Duplicates from Sorted Array II

LeetCode 80 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Keep nums[i] unless it equals nums[insert_index − 2].

நடுத்தரம்ArrayTwo Pointers
LeetCode இல் திற ↗

நான் 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. 1

    The first two elements are always kept; insert_index = 2.

  2. 2

    For each later element, skip it if it matches nums[insert_index − 2].

  3. 3

    Otherwise write it and advance.

  4. 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_index
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Remove 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.