Leetcode Spring Events punch Day: 10.01 face questions array merge sort

Leetcode Spring Events punch Day: The face merge sort an array of questions 10.01

Leetcode Spring Events punch Day: The face merge sort an array of questions 10.01

Thinking

This question, originally ordered two arrays. So we subject completed as double pointer.

A reserved itself and since enough space, so we performed a reverse double pointer, i.e. descending movement, and finally starts directly from the array A covering. This eliminates the need references to additional temporary array.

Regardless of whether the array A valid value will be overwritten. Because only when the position of the array A situation not covered enough valid values ​​to the next case will appear.

Talk is cheap . Show me the code .

class Solution {
public:
    void merge(vector<int>& A, int m, vector<int>& B, int n) {
        int p=m-1,q=n-1,cnt=A.size()-1;
        while(p>=0&&q>=0){
            if(A[p]<=B[q]) A[cnt--]=B[q--];
            else if(A[p]>B[q]) A[cnt--]=A[p--];
        }
        while(q>=0) A[cnt--]=B[q--];
        while(p>=0) A[cnt--]=A[p--];
    }
};

Guess you like

Origin www.cnblogs.com/cell-coder/p/12400301.html