每日一题,最近开题,少写了几次~
今天做的是合并有序数组。做了三种方法:
1、先把B加到A的尾部,然后快排出来的结果。
2、新建一个数组,先把A全部复制进去,然后开始拿,克隆A里面最小的,B里面最小的,按照顺序往A里面放。
3、移动,(类似于插入排序的思想),把B里面的数一个一个拿出来,然后在A中找到它的位置,后面所有元素往后挪动一位。
前两种都是197ms;第三种是196ms。其实都差不多。
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 (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
import java.lang.reflect.Array;
import java.util.ArrayList;
/**
* Created by Mary on 15-1-6.
*/
public class MergeStoreArray {
public static void merge1(int A[], int m, int B[], int n) {
for(int i = 0;i<n;i++){
A[m+i] = B[n-i-1];
}
sort(A,0,m+n-1);
}
private static void sort(int[] array,int low,int high){
if(low>= high){
return;
}
int first = low;
int last = high;
int key = array[low];
while (first<last){
while (first<last && array[last]>=key)
--last;
array[first] = array[last];
while (first<last && array[first]<=key)
++first;
array[last] = array[first];
}
array[first] = key;
sort(array, low, first-1);
sort(array, first+1, high);
}
public static void merge2(int A[], int m, int B[], int n) {
int[] C = new int[m];
System.arraycopy(A,0,C,0,m);
int i = 0;int j = 0;int d = 0;
while (i<m&&j<n){
if(C[i]<B[j]){
A[d]=C[i];
i++;
d++;
continue;
}else if(C[i] > B[j]){
A[d] = B[j];
j++;d++;
continue;
}else {
A[d] = C[i];
d++;
A[d] = B[j];
d++;
i++;j++;
}
}
if(i<m){
for(int t = i;t<m;t++){
A[d] = C[t];
d++;
}
}
if(j<n){
for(int t = j;t<n;t++){
A[d] = B[t];
d++;
}
}
}
public static void merge(int A[], int m, int B[], int n) {
int i=0;
for(int j = 0;j<n;j++){
while (A[i]<B[j] && i<m+j)
i++;
for(int t=m+j;t>i;t--){
A[t] = A[t-1];
}
A[i]=B[j];
i++;
}
}
}