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.
这道题目第一眼看到会想到归并排序里面的合并两个sorted的数组的过程,但是区别之处在于,归并排序使用一个额外的存储空间,但是这里并没有,那么应该如何避免使用额外的存储空间呢?从A、B数组的末尾开始比较、合并。
注意点:很多人好像在代码的结束有两个while循环,其实关于数组A的while循环根本是没必要的,因为如果B内元素已经全部成功归位,那么剩下的A元素原本就是排好序的。
class Solution { public: void merge(int A[], int m, int B[], int n) { int i = m - 1, j = n - 1, k = m + n - 1; while (i >= 0 && j >= 0) A[k--] = A[i] > B[j] ? A[i--] : B[j--]; while (j >= 0)//这里只要判断B即可,因为A原本就在A里面。 A[k--] = B[j--]; } };灰常简洁,不可以再少了。
LeetCode ::Merge Sorted Array[最简短代码],布布扣,bubuko.com
LeetCode ::Merge Sorted Array[最简短代码]
原文:http://blog.csdn.net/u013195320/article/details/22530811