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.
public class Solution { public void merge(int A[], int m, int B[], int n) { int inserted = 0; int i=0; if(B==null||B.length==0){ return; } while(i<m){ if(A[i]>=B[0]){ int temp = A[i]; A[i] = B[0]; B[0] = temp; int j=0; while(j+1<n&&B[j]>B[j+1]){ temp = B[j]; B[j] = B[j+1]; B[j+1] = temp; j++; } } i++; } int j=0; while(j<n){ A[i++]=B[j++]; } } }
中心思想:
有一個迭代器遍歷A裏所有的元素,然後和B裏面的第一個元素比較,如果A的元素大於B的元素,那麼交換,
始終保證B的第一個元素大於A當前遍歷到的元素,並且保證B是有序的。最後把B銜接到A的末尾就行。
算法的複雜度目測是O(n*m)的