[Leetcode] Merge Sorted Array (C++)

题目:

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 and n respectively.

Tag:

Array; Two Pointers

体会:

这个小题,初看很简单,但是实现起来还是有些小地方需要特别注意。首先一个特别的地方就是在A里面merge B。如果是像原始merge算法从头开始merge的话,就可能会出现需要插入操作的地方。(比如需要把B[1]插入到A[2]后)。这时就需要把A[3]到A[last]全部往后移动一位。因为不是链表,明显不合适。但是题目又要求merge到A, 那怎么办呢,解决办法就是从A的屁股上开始merge,就是从大数到小数开始merge。

具体执行的时候,我们的目标就是把B merge 完,即int j = n - 1,  while (j >= 0)就继续执行。

那什么时候选择来自B的元素呢,这里面要注意A的边界情况,即A的元素已经都用完了。所以会有两种情况选择来自B的元素:

一是A的元素用完了 (i.e. i < 0),无条件选择B的;二是当A没完时,有B[j] > A[i]。

 1 class Solution {

 2 public:

 3     void merge(int A[], int m, int B[], int n) {

 4             int i = m - 1;

 5             int j = n - 1;

 6             int k = m + n - 1;

 7             // when B is all merged into A, job done

 8             while (j >= 0) {

 9                 // merge

10                 if (i < 0 || B[j] > A[i]) {

11                     // when A is done or A is less than B, choose B

12                     A[k] = B[j];

13                     j--;

14                 } else {

15                     A[k] = A[i];

16                     i--;

17                 }

18                 k--;

19             }

20         }

21 

22 };

 

你可能感兴趣的:(LeetCode)