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.
class Solution { public: void merge(int A[], int m, int B[], int n) { // Start typing your C/C++ solution below // DO NOT write int main() function int i , j ,temp ; if(n== 0) return ; if(m== 0){ for(i = 0; i < n; i++) A[i] = B[i]; return ; } for(j = 0 ;j< n ;j++) { temp = B[j]; for(i = m-1+j; i>=0; i--) { if(A[i]<= temp) break; else A[i+1] = A[i]; } A[i+1] = temp ; } } };
从后往前处理,寻找大数据插到A的后面,时间复杂度O(m+n)
class Solution { public: void merge(int A[], int m, int B[], int n) { // Start typing your C/C++ solution below // DO NOT write int main() function int cur = m + n -1; int lastA = m-1; int lastB = n-1; while(lastA>= 0 &&lastB >= 0) { A[cur--] = A[lastA] > B[lastB] ? A[lastA--]: B[lastB--]; } while(lastB >= 0) { A[cur--] = B[lastB--] ; } } };