您的位置:首页 > 其它

LeetCode - Merge Sorted Array

2013-12-27 02:08 344 查看
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:

#include <algorithm>
using namespace std;

class Solution {
public:
void merge(int A[], int m, int B[], int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
for(int i = m; i < m + n; ++i){
A[i] = B[i - m];
}
sort(A, A + m + n);
}
};


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:

#include <cstdlib>
using namespace std;

class Solution {
public:
void merge(int A[], int m, int B[], int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int *C = nullptr;

if(nullptr == A || nullptr == B || m < 0 || n <= 0){
return;
}

C = new(nothrow) int[m + n];
if(nullptr == C){
printf("Error: bad memory allocation.");
exit(0);
}
int i, j, k;

i = j = k = 0;
while(i < m && j < n){
if(A[i] < B[j]){
C[k++] = A[i++];
}else{
C[k++] = B[j++];
}
}
while(i < m){
C[k++] = A[i++];
}
while(j < n){
C[k++] = B[j++];
}
memcpy(A, C, (m + n) * sizeof(A[0]));
delete[] C;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: