Merge Sorted Array
Description
Given two sorted integer arrays A and B, merge B into A as one sorted array.
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
既然两个数组已经排好序了,那么我们只需两边遍历一下,并比较大小就OK了。
public class Solution { /** * @param A: sorted integer array A * @param B: sorted integer array B * @return: A new sorted integer array */ public int[] mergeSortedArray(int[] A, int[] B) { // write your code here int[] C = new int[A.length+B.length]; int i = A.length - 1; int j = B.length - 1; int index = i+j+1; while(i >= 0 || j >= 0){ if(i < 0){ C[index--] = B[j--]; }else if(j < 0){ C[index--] = A[i--]; }else if(A[i] > B[j]){ C[index--] = A[i--]; }else{ C[index--] = B[j--]; } } return C; } }
坑爹,没看清题目,以为A足够大,害我一直数组越界。。。原来是要我们新建一个数组