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.