LeetCode - Merge Sorted Array

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 };

 

你可能感兴趣的:(LeetCode)