📜  leetcoe 88 (1)

📅  最后修改于: 2023-12-03 15:32:38.156000             🧑  作者: Mango

LeetCode 88

Introduction

LeetCode 88 problem is called "Merge Sorted Array". It is a well-known problem among programmers. Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Example

Input:

nums1 = [1,2,3,0,0,0], m = 3

nums2 = [2,5,6], n = 3

Output:

[1,2,2,3,5,6]

Explanation:

The arrays are merged as [1,2,2,3,5,6] and sorted in ascending order.

Solution

The solution to this problem is to use a two-pointer approach. We start from the end of both arrays and move the pointers towards the beginning. We compare the elements at the pointers' positions and place them in order in the first array. We continue the process until all elements in the second array are merged into the first array.

Here is the code snippet for the solution:

def merge(nums1, m, nums2, n):
    i = m - 1
    j = n - 1
    k = m + n - 1
    
    while i >= 0 and j >= 0:
        if nums1[i] > nums2[j]:
            nums1[k] = nums1[i]
            i -= 1
        else:
            nums1[k] = nums2[j]
            j -= 1
        k -= 1
    
    while j >= 0:
        nums1[k] = nums2[j]
        j -= 1
        k -= 1
Conclusion

LeetCode 88 problem is a good problem to practice array manipulation and two-pointer techniques. The solution is relatively simple and provides a great opportunity to practice algorithmic thinking.