LeetCode – 88. Merge Sorted Array

Given two sorted integer arraynums1 and nums2, merge nums2 into nums1 as one sorted array.

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

public class Solution {
    public void merge(int A[], int m, int B[], int n) {
        int a = m -1;
        int b = n -1;
        int l = m+n -1;
        while(a>=0 && b >=0){
            if(A[a] > B[b]){
                A[l] = A[a];
                a--;
            }
            else{
                A[l] = B[b];
                b--;
            }
            l--;
        }
        while(b>=0){
            A[l] = B[b];
            l--;
            b--;
        }
    }
}

This site Original article All followed" Attribution—NonCommercial—ShareAlike 4.0 (CC BY-NC-SA 4.0) ”。 Please keep the following marks for sharing and interpretation:

Original author: Jake Tao Source: 「LeetCode – 88. Merge Sorted Array」

Praise 133
0 0 133

Further reading

Post a reply

Log in can only be commented on later
Share this page
Back to top