Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note: You have to modify the array A to contain the merge of A and B. Do not output anything in your code. TIP: C users, please malloc the result into a new array and return the result.
If the number of elements initialized in A and B are m and n respectively, the resulting size of array A after your code is executed should be m + n
Example :
Input :
A : [1 5 8]
B : [6 9]
Modified A : [1 5 6 8 9]
My Solution:
public class Solution {
public void merge(ArrayList<Integer> a, ArrayList<Integer> b) {
int i=0,j=0;
ArrayList<Integer> al= new ArrayList<Integer>();
while(i<a.size() && j<b.size()){
if(a.get(i)<b.get(j)){
al.add(a.get(i));
i++;
}
else{
al.add(b.get(j));
j++;
}
}
while(i<a.size()){
al.add(a.get(i));
i++;
}
while(j<b.size()){
al.add(b.get(j));
j++;
}
}
I created a 3rd ArrayList where I merged all elements of both 1st and 2nd ArrayLists. Now I have to copy all the elements of 3rd ArrayList into 1st one. I'm stuck now. Because, when I resized it by using
public static void ensureSize(ArrayList<Integer> list, int size){
list.ensureCapacity(size);
while(list.size()<size){
list.add(null);
}
}
ensureSize(a,al.size());
for(int k=0;k<al.size();k++){
a.set(k,al.get(k));
}
It's giving me ArrayIndexOutOfBound error. I tried Collections.copy(a,al), it too didn't work.
arrays, but your code is usingArrayList?