标签:面试 leetcode algorithm merge sorted array 合并有序数组
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 (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 andn respectively.
合并两个数组为一个有序数组,这题也很简单,唯一考查的地方就是怎么处理数组,是从前往后还是从后往前。一般情况,从后往前的效率比从前往后高,也要省不少事。代码如下,从后开始合并。
class Solution { public: void merge(int A[], int m, int B[], int n) { if(B==NULL || n<=0) return ; if(A==NULL || m<=0) { for(; n>0; --n) A[n-1] = B[n-1]; return ; } int i=m-1, j=n-1, k = m+n-1; while(i>=0 && j>=0){ if(A[i]>B[j]) A[k--] = A[i--]; else A[k--] = B[j--]; } while(j>=0) A[k--] = B[j--]; } };
[LeetCode] Merge Sorted Array [22],布布扣,bubuko.com
[LeetCode] Merge Sorted Array [22]
标签:面试 leetcode algorithm merge sorted array 合并有序数组
原文地址:http://blog.csdn.net/swagle/article/details/29378433