leetcode每日一练:两个排序数组的中值(java)

题目 :

有两个排序数组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;
}
}

天天一练,天天都开心。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值