Created
January 15, 2013 15:02
-
-
Save pdu/4539238 to your computer and use it in GitHub Desktop.
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. http://leetcode.com/onlinejudge#question_88
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Solution { | |
| public: | |
| void merge(int A[], int m, int B[], int n) { | |
| int *C = new int[m]; | |
| memcpy(C, A, m * sizeof(int)); | |
| int i = 0, j = 0; | |
| int id = 0; | |
| while (i < m || j < n) { | |
| if (i == m) | |
| A[id++] = B[j++]; | |
| else if (j == n) | |
| A[id++] = C[i++]; | |
| else if (C[i] < B[j]) | |
| A[id++] = C[i++]; | |
| else | |
| A[id++] = B[j++]; | |
| } | |
| delete[] C; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment