Leetcode平台上的Median of Two Sorted Arrays题目,大意就是找两个已排序数组的中位数。今天先用快排的方式实现一下,代码如下:
快排递归深度logn,每一层的操作复杂度是O(n)所以复杂度应该是O(nlogn)。
There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
public class Solution {
public static int[] C;
public static void quickSort(int a[],int low, int high){
if(low < high){
int i = low;
int tmp;
for(int j = low; j< high; j++){
if(a[j]<=a[high]){
tmp = a[i];
a[i] = a[j];
a[j] = tmp;
++ i;
}
}
tmp = a[i];
a[i] = a[high];
a[high] = tmp;
quickSort(a,low,i-1);
quickSort(a,i+1,high);
}
}
public static double findMedianSortedArrays(int A[], int B[]) {
double i ;
//combine these two arrays into a new array C
int l = A.length+B.length;
C = new int[l];
System.arraycopy(A, 0, C, 0, A.length);
System.arraycopy(B, 0, C, A.length, B.length);
quickSort(C,0,l-1);
//for(int ii = 0; ii < l; ii ++)
//System.out.println(C[ii]);
if(l%2 == 0)
i = (double) ((C[l/2]+C[l/2-1])/2.0);
else
i = (double) C[(l-1)/2];
return i;
}
public static void main(String args[]){
int[] A = {1};
int[] B = {};
double median = findMedianSortedArrays(A,B);
System.out.println(median);
}
}
快排递归深度logn,每一层的操作复杂度是O(n)所以复杂度应该是O(nlogn)。
对于快排能AC我表示相当意外,只能说leetcode平台给的测试用例不够强壮。如果给一个倒序排好序的数组,我这个快排就死掉了,相当于冒泡阿。
今天再用堆的思想实现一下,复杂度应该比这个快排低一些。
谢谢木易先森的指导!