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

Merge Sorted Array

LeetCode 88 · எளிது · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Three pointers, filling nums1 from the end.

எளிதுArrayTwo PointersSorting
LeetCode இல் திற ↗

நான் Merge Sorted Array (LeetCode 88) ஐ இப்படித் தீர்த்தேன் — Two Pointers பேட்டர்னின் ஒரு எளிது பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.

கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.

Intuition

nums1 has empty space at the end, so fill it from the back. Compare the largest remaining element of each array and drop the larger one into the last free slot; nothing you still need is ever overwritten.

Approach

  1. 1

    r1 = m−1, r2 = n−1, k = m+n−1.

  2. 2

    While both have elements, move the larger to nums1[k].

  3. 3

    Copy any leftovers from nums2 (leftovers in nums1 are already in place).

நான் எப்படித் தீர்த்தேன்

Three pointers from the endPythonO(m+n) time · O(1) space
class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        k = m+n-1
        r1=m-1
        r2=n-1
        while r1>=0 and r2>=0:
            if nums1[r1]>nums2[r2]:
                nums1[k]=nums1[r1]
                r1-=1
            else:
                nums1[k]=nums2[r2]
                r2-=1
            k-=1
        while r1>=0:
            nums1[k]=nums1[r1]
            r1-=1
            k-=1
        while r2>=0:
            nums1[k]=nums2[r2]
            r2-=1
            k-=1
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Merge Sorted Array — அடிக்கடி கேட்கப்படும் கேள்விகள்

Merge Sorted Array பின்னாலுள்ள intuition என்ன?

nums1 has empty space at the end, so fill it from the back. Compare the largest remaining element of each array and drop the larger one into the last free slot; nothing you still need is ever overwritten.

Merge Sorted Array (LeetCode 88) ஐ எப்படித் தீர்ப்பது?

1. r1 = m−1, r2 = n−1, k = m+n−1. 2. While both have elements, move the larger to nums1[k]. 3. Copy any leftovers from nums2 (leftovers in nums1 are already in place).

Merge Sorted Array இன் time மற்றும் space complexity என்ன?

Time: O(m + n). Space: O(1). (Accepted approach: Three pointers from the end.)

Merge Sorted Array இல் பொதுவான தவறுகள் என்ன?

Filling from the front would overwrite elements of nums1 you haven't placed yet.