Peter Tsung
Peter Tsung

Reputation: 945

Merge Sorted Array in leetcode

i saw this in https://leetcode.com/problems/merge-sorted-array/description/ and the answer in https://leetcode.com/problems/merge-sorted-array/discuss/29503/Beautiful-Python-Solution

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

I have two doubts:

  1. When i want to run the code print(Solution().merge([1, 2, 3], 3, [4, 5, 6], 3)) and it just gave me an error hint IndexError: list assignment index out of range.
  2. I don't quite understand the methodology in the answer above. Could someone tell me how to solve this kind of problem?

Upvotes: 0

Views: 880

Answers (3)

Anurath Mane
Anurath Mane

Reputation: 47

Java code to merge two sorted Arrays

Given two sorted arrays, the task is to merge them in a sorted manner.

Input: arr1[] = { 1, 3, 4, 5}, arr2[] = {2, 4, 6, 8} 
Output: arr3[] = {1, 2, 3, 4, 4, 5, 6, 8}

Input: arr1[] = { 5, 8, 9}, arr2[] = {4, 7, 8} 
Output: arr3[] = {4, 5, 7, 8, 8, 9} 

Try with Different combination of two input arrays and compare expected array

import java.util.Arrays;

public class MergeArraysDemo {

    public static void main(String[] args) {
     int arr1[] = { 1, 3, 5, 7 };
        int arr2[] = { 2, 4, 6, 8 };
        int arr3[] = mergeArrays(arr1, arr2);
        System.out.println("Array after merging - " + Arrays.toString(arr3));
    }

    public static int[] mergeArrays(int[] arr1, int[] arr2) {
        int n = arr1.length;
        int m = arr2.length;
        int[] arr3 = new int[n + m];
        int j = 0;
        int k = 0;
        int min = 0;
        boolean flg = false;

        for (int i = 0; i < n + m; i++) {
            if (j < n && k < m) {
                min = arr2[k];
                if (arr1[j] <= min) {
                    arr3[i] = arr1[j];
                    j++;
                    flg = false;
                } else {
                    arr3[i] = min;
                    k++;
                    flg = true;
                }
            } else {
                if (flg) {
                    arr3[i] = arr1[n - 1];
                } else {
                    arr3[i] = min;
                }
            }
        }

        return arr3;
    }

}

Upvotes: -1

Soumya Ranjan Rout
Soumya Ranjan Rout

Reputation: 413

def merge_two_sorted_arrays(left: list, right: list) -> list:
    """
    Merge Sorted Array in leetcode
    Args:
        left: left array
        right: right array

    Returns: A new merged array
    """
    A = [None] * (len(left) + len(right))
    i = j = k = 0
    while i < len(left) and j < len(right):
        if left[i] < right[j]:
            A[k] = left[i]
            i += 1
        else:
            A[k] = right[j]
            j += 1
        k += 1
    while i < len(left):
        A[k] = left[i]
        i += 1
        k += 1
    while j < len(right):
        A[k] = right[j]
        j += 1
        k += 1

    return A


a = [1, 2, 2, 4]
b = [3, 5, 6, 9]

print(merge_two_sorted_arrays(a, b))

Output:

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

Upvotes: 0

iBug
iBug

Reputation: 37247

The problem is here:

def merge(self, nums1, m, nums2, n):
    while m > 0 and n > 0:
        if nums1[m-1] >= nums2[n-1]:
            nums1[m+n-1] = nums1[m-1]   # nums1[m+n-1] IndexError
            m -= 1
        else:
            nums1[m+n-1] = nums2[n-1]   # Same as above
            n -= 1
    if n > 0:
        nums1[:n] = nums2[:n]

You may want to "resize" the list first to prevent index error:

def merge(self, nums1, m, nums2, n):
    nums1 += nums2
    # Or nums1 += [None] * len(nums2)

    while m > 0 and n > 0:
        if nums1[m-1] >= nums2[n-1]:
            nums1[m+n-1] = nums1[m-1] # nums1[m+n-1] IndexError
            m -= 1
        else:
            nums1[m+n-1] = nums2[n-1] # Same as above
            n -= 1
    if n > 0:
        nums1[:n] = nums2[:n]

Upvotes: 1

Related Questions