找中位数

无序数组找中位数

  1. 排序后再找 时间复杂度为O(nlogn)
  2. 建立大小为n/2+1的最大堆,如果比堆顶大的则舍去如果是奇数则堆顶就是中位数
    如果是偶数则取出两位求平均值 o(nlogk)
  3. parition操作
    建立一个partition方法
    partition(int[] arr , int start , int end){
    int left = start;
    int right = end;
    int key = arr[end]; //选取关键字
    while (left < right)
    {
    while (left < right && arr[left] <= key) //左边找比key大的值
    {
    ++left;
    }
    while (left < right && arr[right] >= key) //右边找比key小的值
    {
    –right;
    }
    if (left < right)
    {
    swap(arr[left], arr[right]); //找到之后交换左右的值
    }
    }
    swap(arr[right], arr[end]);
    return left;

}

int getMidnum(int[] arr ){
if(arrnull||arr.length0)
return -1;
int mid = (arr.length-1)/2
int div = PartSort(arr,0,arr.length);
while (div != mid)
{
if (mid < div) //左半区间找
div = PartSort(arr, start, div - 1);
else //左半区间找
div = PartSort(arr, div + 1, end);
}
return arr[mid]; //找到了

}

两个有序数组找中位数

    int m = a.length;
    int n = b.length;
    if(m>n){
    int[] temp = a;
    a = b;
    b = a;
    int tem = m;
    m = n;
    n= m;
    }
    int start = 0;
    int end = m;
    int mid = (m+n+1)/2;
    while(start<end){
    int i = (start + end )/2;
    int j = mid -i;
    if(i<end&&arrayB[j-1]>arrayA[i]{
    start = i +1;
    else if(i>start&&arrayA[i-1]>arrayB[j]
    end = i-1;
    else {
	
}
    
    

你可能感兴趣的:(LeetCode)