合并两个排序的整数数组A和B变成一个新的数组。
样例
给出 A = [1, 2, 3, empty, empty], B = [4, 5]合并之后 A 将变成 [1,2,3,4,5]
看起来很简单的一道题,然后本来用一个循环来insert再排一次序就好了。
class Solution {
/**
* @param A: sorted integer array A which has m elements,
* but size of A is m+n
* @param B: sorted integer array B which has n elements
* @return: void
*/
public void mergeSortedArray(int[] A, int m, int[] B, int n) {
// write your code here
for(int i=m,l=m+n;i<l;i++){
A[i]=B[i-m];
}
for(int i=0,l=A.length;i<l;i++){
for(int j=0;j<l;j++){
if(A[i]<A[j]){
int tmp=A[i];
A[i]=A[j];
A[j]=tmp;
}
}
}
}
}
前面的数据都通过了,后来毫无意外的发现数据测试里又有大量数据的测试,结果肯定又Time Limit Exceeded了。
后来想,前面插入的时间复杂度为o(N),这个不用管了,后面排序的复杂度是o(N^2),估计就是这一步出问题了。
(展现算法功力的时候到了)于是现在有两个思路,第一个思路就是在insert的时候检测,直接insert到合适的位置,省了排序这一个步骤;另一个办法就是采用更高效率的排序方法。
然后我决定先试试用第二种方法,先使用快排来重写排序的部分。
(然后我发现我半年前看的快排忘得差不多了。。得去补一下,等一下写一篇关于排序的博客)
我回来填坑了。
复习完了各种排序以后(排序的文章地址:http://blog.csdn.net/macuilx0chitl/article/details/54588514),我使用快排来重写排序的部分。
class Solution {
/**
* @param A: sorted integer array A which has m elements,
* but size of A is m+n
* @param B: sorted integer array B which has n elements
* @return: void
*/
public void mergeSortedArray(int[] A, int m, int[] B, int n) {
// write your code here
for(int i=m,l=m+n;i<l;i++){
A[i]=B[i-m];
}
quickSort(A);
}
private static void quickSort(int[] arr) {
qs(arr, 0, arr.length - 1);
}
private static void qs(int[] arr, int start, int end) {
if (start == end) {
return;
}
int base = start;
int left = start + 1;
int right = end;
while (true) {
while ((arr[right] >= arr[base]) && (right > left)) {
right--;
} // 从右往左移动,直到找到一个数字小于base
while ((arr[left] <= arr[base]) && (left < right)) {
left++;
} // 从左往右 移动,直到找到一个数字大于base
if (right == left) {
if (arr[left] < arr[base]) {
int tmp = arr[base];
arr[base] = arr[left];
arr[left] = tmp;
}
break;
} else {
int tmp = arr[right];
arr[right] = arr[left];
arr[left] = tmp;
}
}
qs(arr, start, right - 1);
if (right > end) {
qs(arr, end, end);
} else {
qs(arr, right , end);
}
}
}
使用了快速排序以后,通过了,耶。
爽。毕竟第一种思路实现起来比较复杂一点,省事了。