Problem
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.
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.
Code
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 = new int[m + n]; int i = 0,j = 0; while(i < m || j < n){ if(i < m && j < n){ if(A[i] < B[j]){ C[i + j] = A[i]; ++i; } else{ C[i + j] = B[j]; ++j; } } else if(i < m){ C[i + j] = A[i]; ++i; } else{ C[i + j] = B[j]; ++j; } } copy(C,C + m + n,A); }
No comments:
Post a Comment