題目:web
合併兩個排序的整數數組A和B變成一個新的數組。ide
樣例spa
給出A = [1, 2, 3, empty, empty] B = [4,5]code
合併以後A將變成[1,2,3,4,5]orm
注意 blog
你能夠假設A具備足夠的空間(A數組的大小大於或等於m+n)去添加B中的元素。排序
解題:ci
這裏給的是兩個數組,上題給的是ArrayList格式,比較好處理,從新定義一個長度m+n的數組,可是A的數組長度是m+n,能夠從後面將元素插入的A數組中element
class Solution { /** * @param A: sorted integer array A which has m elements, * but size of A is m+n * @param B: sorted integer array B which has n elements * @return: void */ public void mergeSortedArray(int[] A, int m, int[] B, int n) { // write your code here int k = m + n -1; m--; n--; while(m>=0 && n>=0){ if(A[m] >= B[n]){ A[k--] = A[m--]; }else{ A[k--] = B[n--]; } } while(n>=0){ A[k--] = B[n--]; } } }
也能夠這樣寫
class Solution { /** * @param A: sorted integer array A which has m elements, * but size of A is m+n * @param B: sorted integer array B which has n elements * @return: void */ public void mergeSortedArray(int[] A, int m, int[] B, int n) { // write your code here int k = m + n -1; m--; n--; while(k>=0){ if(n<0 || (m>=0 && A[m] >= B[n])){ A[k--] = A[m--]; }else{ A[k--] = B[n--]; } } } }
Python程序:
class Solution: """ @param A: sorted integer array A which has m elements, but size of A is m+n @param B: sorted integer array B which has n elements @return: void """ def mergeSortedArray(self, A, m, B, n): # write your code here for i in range(n): A[m+i] = B[i] A.sort() return A
總耗時: 233 ms