Skip to content

Instantly share code, notes, and snippets.

@pdu
Created January 15, 2013 15:02
Show Gist options
  • Select an option

  • Save pdu/4539238 to your computer and use it in GitHub Desktop.

Select an option

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