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

मी 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.