【Leetcode】【Easy】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 mand n respectively.

解题思路:

1、合并两个有序数列,并且数列A已经具有充足的空间以供合并。

2、采取从后向前填入的方式,避免了空间冲突,o(n+m)

解题步骤:

1、新建三个变量,合并后数列的index,用于遍历a、b的aIndex、bIndex

2、循环开始,循环条件是aIndex和bIndex都不为0,因为需要比较后再插入:

  (1)将较大的一方插入后端,同时递减;

3、因为是在A上操作,当循环结束,而A还有剩余,就刚好放在原位置不变;如果B还有剩余,那么将B值复制到A中;

 1 class Solution {
 2 public:
 3     void merge(int A[], int m, int B[], int n) {
 4         int index = m + n - 1;
 5         int aIndex = m - 1;
 6         int bIndex = n - 1;
 7         
 8         while(aIndex >= 0 && bIndex >= 0) {
 9             A[index--] = B[bIndex] > A[aIndex] ? B[bIndex--] : A[aIndex--];
10         }
11         
12         while(bIndex >= 0) {
13             A[index--] = B[bIndex--];
14         }
15     }
16 };

另,

我第一次做的时候,写了很多代码来判断A和B的排序方式。根据不同的排序方式,比如同为由大到小或同为由小到大,或者相互不一样,对应的写不同的合并代码。

看了别人的解答后,才发现已经默认A和B都是由小到大排列的...不知道是如何从题目得知的...

原文地址:https://www.cnblogs.com/huxiao-tee/p/4195842.html