LeetCode - Merge Sorted Array

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 to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.

http://oj.leetcode.com/problems/merge-sorted-array/


Solution:

We need to merge B into A and A has enough space to hold B. So we can start from the end of new A. Compare the element in A and B and add the larger number into new position. Be careful if the size of B is larger than A.

https://github.com/starcroce/leetcode/blob/master/merge_sorted_array.cpp

// 32 ms for 59 cases
class Solution {
public:
    void merge(int A[], int m, int B[], int n) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int indexA = m-1, indexB = n-1, index = m+n-1;
        while(indexA >= 0 && indexB >= 0) {
            A[index] = A[indexA] >= B[indexB] ? A[indexA--] : B[indexB--];
            index--;
        }
        while(indexB >= 0) {
            A[index] = B[indexB];
            index--;
            indexB--;
        }
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章