题目 :
有两个排序数组s1和s2大小分别为m和n。
找到两个排序数组的中间值。总的运行时复杂度应该是O(log(m+n)。
你可以假设s1和s2不可能都是空的。
例1:
nums1 = [1, 3]
nums2 = [2];
The median is 2.0。
思想(可能性能略差):先将俩数组合并为一个数组,再利用快速排序将数组排序,再判断找出中间值。
代码:
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int t=nums1.length+nums2.length;
int[] c=new int[t];
//合并俩数组
System.arraycopy(nums1, 0, c, 0, nums1.length);
System.arraycopy(nums2, 0, c, nums1.length, nums2.length);
//将新建数组排序
sort(c,0,t-1);
int k;
k=(t-1)/2;
找出新建数组中间值
if(t%2==0){
return (double)(c[k]+c[k+1])/2;
}
else{
return (double)c[k];
}
}
public void sort(int[] c,int low,int high){
int pivot;
if(low<high){
pivot=partition(c,low,high);
sort(c,low,pivot-1);
sort(c,pivot+1,high);
}
}
public int partition(int[] c,int low,int high){
int pivotkey=c[low];
while(low<high){
while(c[high]>=pivotkey && low<high)
high--;
swap(c,low,high);
while(c[low]<=pivotkey && low<high)
low++;
swap(c,low,high);
}
return low;
}
public void swap(int[] c,int low,int high){
int flag;
flag=c[low];
c[low]=c[high];
c[high]=flag;
}
}
天天一练,天天都开心。