随笔- 509  文章- 0  评论- 151  阅读- 22万 

Merge Sorted Array

2013.12.27 01:18

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 to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.

Solution1:

  First solution is simple and foolish enough, just put them together and sort it.

  Time complexity is O((m + n) * log(m + n)), space complexity is O(1).

Accepted code:

复制代码
 1 #include <algorithm>
 2 using namespace std;
 3 
 4 class Solution {
 5 public:
 6     void merge(int A[], int m, int B[], int n) {
 7         // IMPORTANT: Please reset any member data you declared, as
 8         // the same Solution instance will be reused for each test case.
 9         for(int i = m; i < m + n; ++i){
10             A[i] = B[i - m];
11         }
12         sort(A, A + m + n);
13     }
14 };
复制代码

Solution2:

  Merge two arrays with O(m + n) extra space. Time complexity is O(m + n), space complexity is O(m + n). In-place merge seems more efficient, but somewhat a little tricky to understand. I'll put my in-place merge solution here when I grab the idea.

  Time complexity is O(m + n), space complexity is O(m + n).

Accepted code:

复制代码
 1 #include <cstdlib>
 2 using namespace std;
 3 
 4 class Solution {
 5 public:
 6     void merge(int A[], int m, int B[], int n) {
 7         // IMPORTANT: Please reset any member data you declared, as
 8         // the same Solution instance will be reused for each test case.
 9         int *C = nullptr;
10         
11         if(nullptr == A || nullptr == B || m < 0 || n <= 0){
12             return;
13         }
14         
15         C = new(nothrow) int[m + n];
16         if(nullptr == C){
17             printf("Error: bad memory allocation.");
18             exit(0);
19         }
20         int i, j, k;
21         
22         i = j = k = 0;
23         while(i < m && j < n){
24             if(A[i] < B[j]){
25                 C[k++] = A[i++];
26             }else{
27                 C[k++] = B[j++];
28             }
29         }
30         while(i < m){
31             C[k++] = A[i++];
32         }
33         while(j < n){
34             C[k++] = B[j++];
35         }
36         memcpy(A, C, (m + n) * sizeof(A[0]));
37         delete[] C;
38     }
39 };
复制代码

 

 posted on   zhuli19901106  阅读(222)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示