Woodstock Blog

a tech blog for general algorithmic interview questions

[LeetCode 88] Merge Sorted Array

Question

link

Given two sorted integer arrays A and B, merge B into A as one sorted array.

Note:
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.

Stats

Frequency 5
Difficulty 2
Adjusted Difficulty 1
Time to use --------

Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red)

Analysis

This is an easy question.

Solution

Just insert from the end to the head.

Code

public void merge(int A[], int m, int B[], int n) {
    int p1 = m - 1, p2 = n - 1;
    for (int i = m + n - 1; i >= 0; i --){
        if (p2 == -1) return;
        if (p1 == -1) {
            for (int j = 0; j <= p2; j++) A[j] = B[j];
            return;
        }
        if (A[p1] > B[p2]) A[i] = A[p1--];
        else A[i] = B[p2--];
    }
}