# I am trying to use vector to solve the problem but failed. Hope someone could give me some suggestions

• I am trying to store all the sorted value to a vector and then pop to A[], I kept got runtime error. Hope someone could give me a hint what i am missing. Thanks a lot.
I actually run my program and putting the test data. There is no problem http://postimg.org/image/3pv7drr0x/,
and this http://postimg.org/image/3rjnms9wn/

``````  class Solution {
public:
void merge(int A[], int m, int B[], int n){
//m is total, (m-n) is the actual number in A[]
vector<int> a;
int left;//what's left
int total=m;
m=m-n;//now m is A[]'s real contain value

while(m!=0 && n!=0)
{
if(A[m-1]>B[n-1])
{a.push_back(A[m-1]);
m--;}
else
{a.push_back(B[n-1]);
n--;}
}
left=m+n;
//----------------this is for push back the left to vector
if(m==0)
{
while(left!=0)
{
a.push_back(B[left-1]);
left--;
}
}
else if(n==0)
{
while(left!=0)
{
a.push_back(A[left-1]);
left--;
}
}
//----------------this is for push back the left to vector
for(int i=0;i<total;i++)
{
A[i]=a.back();
a.pop_back();
}
}
};
``````

• You may just create a vector v with array A elements and then keep two pointers in v and array B, and then keep moving the smaller of the two in array A until one of vector v or array B become empty, after which you may copy the remaining in array A.

``````void merge(int A[], int m, int B[], int n) {
vector<int> v(A, A+m) ;
int i = 0, j = 0, k = 0 ;
while(i < m && j < n) {
if(v[i] <= B[j]) {
A[k++] = v[i] ;
i++ ;
}
else {
A[k++] = B[j] ;
j++ ;
}
}
while(i < m) {
A[k++] = v[i] ;
i++ ;
}
while(j < n) {
A[k++] = B[j] ;
j++ ;
}
}``````

• Thanks a lot for replying.

• You don't really need vector to solve this problem; Just think about scanning from the rightmost

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.