Leetcode平台上的Median of Two Sorted Arrays题目用Java快排实现

上一篇 / 下一篇  2014-05-28 17:04:24 / 个人分类:学习

Leetcode平台上的Median of Two Sorted Arrays题目,大意就是找两个已排序数组的中位数。今天先用快排的方式实现一下,代码如下:

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平台给的测试用例不够强壮。如果给一个倒序排好序的数组,我这个快排就死掉了,相当于冒泡阿。

今天再用堆的思想实现一下,复杂度应该比这个快排低一些。

谢谢木易先森的指导!

TAG:

 

评分:0

我来说两句

我的栏目

日历

« 2024-05-03  
   1234
567891011
12131415161718
19202122232425
262728293031 

数据统计

  • 访问量: 17770
  • 日志数: 12
  • 建立时间: 2014-05-21
  • 更新时间: 2014-06-03

RSS订阅

Open Toolbar