首页 > 其他 > 详细

LeetCode ---- Merge Sorted Array

时间:2014-06-16 11:10:02      阅读:387      评论:0      收藏:0      [点我收藏+]

题目链接

Problem discription

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.

Accpted Code 1 ( use extra space)

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     void merge(int A[], int m, int B[], int n) {
 4         // we use "ai" and "bi" to keep trace 
 5         // of array A[] and B[] respectively
 6         // "ci" holds the number of elements that 
 7         // has been merged
 8         int ai = 0, bi = 0, ci = 0;
 9         // create an extra vector of size n+m 
10         // to keep the sorted array
11         vector<int> C(n + m);
12         while (ci < n + m) {
13             // from small to large 
14             if (ai < m && (bi >= n || A[ai] <= B[bi])) {
15                 C[ci++] = A[ai++];
16             } else {
17                 C[ci++] = B[bi++];
18             }
19         }
20         // copy the sorted array from C to A
21         for (int i = 0; i < n+m; i++) A[i] = C[i];
22     }
23 };
bubuko.com,布布扣

Accepted Code (without extra space) Clear & Simple

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     void merge(int A[], int m, int B[], int n) {
 4         // we use "ai", "bi" to iterator A[] and B[] 
 5         // from the end respectively
 6         // since the size of A[] equal to or greater n+m
 7         // thus we can use inplace sort by filling A[]
 8         // from A[n+m-1] to A[0]
 9         int ai = m - 1, bi = n - 1, ci = n + m - 1;
10         while (ci >= 0) {
11             if (ai >= 0 && (bi < 0 || A[ai] >= B[bi])) {
12                 A[ci--] = A[ai--];
13             } else {
14                 A[ci--] = B[bi--];
15             }
16         }
17     }
18 };
bubuko.com,布布扣

 

LeetCode ---- Merge Sorted Array,布布扣,bubuko.com

LeetCode ---- Merge Sorted Array

原文:http://www.cnblogs.com/Stomach-ache/p/3783411.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!