码迷,mamicode.com
首页 > 编程语言 > 详细

[Leetcode] Merge Sorted Array (C++)

时间:2014-10-26 00:21:33      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   sp   div   on   

题目:

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,会出现需要插入操作,然后把A剩下的部分后移,因为不是链表,明显不合适。但是题目又要求merge到A, 那怎么办呢,解决办法就是从A的屁股上开始merge,就是从大数到小数开始merge。

具体执行的时候,我们的目标就是把Bmerge 完,即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 merged, 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] Merge Sorted Array (C++)

标签:style   blog   color   io   os   ar   sp   div   on   

原文地址:http://www.cnblogs.com/stevencooks/p/4051207.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!