zoukankan      html  css  js  c++  java
  • 转 求中位数

     public double findMedianSortedArrays(int A[], int B[]) {
                    // Start typing your Java solution below
                    // DO NOT write main() function
                     
                    int m = A.length, n = B.length;
                     
                    //if m+n is even, then the median is the average of (m+n)/2 and (m+n)/2 - 1
                    //if m+n is odd, then the median is (m+n)/2
             
                    int mid = (m+n)/2;
                    //look for mid in A
                    //[start, end]: close region to try. inclusive.
                    int start = 0, end = m-1, i = 0, j = 0;
                    int median = 0;
                    while (start <= end) {
                        i = (start+end)/2;
                        j = mid - i;
                        if (get(B, j-1) <= get(A, i) && get(A, i) <= get(B, j)) //index out of bound here.
                        {
                            median = get(A, i);
                            break;
                        }
                        else if (get(A, i)< get(B, j-1)) { //A[i] is smaller than the median
                            start = i + 1;
                            i = (start+end)/2;
                            j = mid - i;
                        }
                        else if (get(A, i) > get(B, j)) { //A[i] is bigger than the median
                            end = i - 1;
                            i = (start+end)/2;
                            j = mid - i;
                        }
                    }
                     
                    if (start <= end) //found the median
                    {
                        if ((m+n) % 2 == 0) { //index out of bound here
                            int other = Math.max(get(A, i-1), get(B, j-1));
                            return (median + other) * 0.5;
                        }
                        else {
                            return (double)median;
                        }
  • 相关阅读:
    位置控制
    Scaleform结合C++编程
    使用定点缓存进行绘制
    纹理
    动态规划:背包问题
    希尔排序
    折半插入排序
    快速排序
    上楼梯算法
    归并排序
  • 原文地址:https://www.cnblogs.com/happinessqi/p/3578536.html
Copyright © 2011-2022 走看看