您的位置:首页 > 其它

LeetCode Merge Sorted Array

2015-01-27 14:34 363 查看
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 mand n respectively.
思路分析:这题开始向从前向后merge,发现需要shift A中的元素,让算法复杂度变高。根据这个题目的假定,A刚好可以容纳A和B中的元素,于是我们可以从后向前merge,这样做的好处是,可以对A从后向前填入数,而不会覆盖前面尚未填入的数。通过三个指针的移动,比较当前的A和B元素值,还是很好实现的。注意|| &&这些操作符的短路效应。时间复杂度O(m+n),空间复杂度O(1)。
AC Code
public class Solution {
    public void merge(int A[], int m, int B[], int n) {
         int pa = m - 1, pb = n - 1, pc = m + n -1;
         for(; pc >= 0; pc--){
             if(pa >= 0 && (pb < 0 || A[pa] > B[pb] )){
                 A[pc] = A[pa--];
             } else {
                 A[pc] = B[pb--];
             }
         }
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: