算法 - 查找第K大数字

栏目: 编程工具 · 发布时间: 6年前

内容简介:本题目借助快排思想,算法描述:代码:算法复杂度分析:

本题目借助快排思想,算法描述:

  • a为待 排序 数组,n为数组长度
  1. 问题转换:把第k大数字转换成第l小数字,比如: n=5,k=1 ,那么 l=n-k+1=5 ,也就是第5小的数字,其下标 l_i=5-1=4
  2. a[n-1] 作为 pivot
  3. 用快排的思路,把 < pivot 的元素放到 pivot 左边,把 >= pivot 的元素放到 pivot 右边,得到pivot的下标: pivot_i
  4. 如果 pivot_i < l_i ,则说明被查找的数字可能在右边,对右边重复2-5步骤
  5. 如果 pivot_i > l_i ,则说明被查找的数字可能在左边,对左边重复2-5步骤

代码:

public static int findKthBigNumber(int[] a, int kthBig) {
  int n = a.length;
  int lthSmall = n - kthBig;
  return quickFind(a, 0, a.length - 1, lthSmall);
}

private static int quickFind(int[] a, int start, int end, int lthSmall) {
  if (start > end) {
    return -1;
  }
  int pivot = a[end];

  int pivot_i = start;
  for (int j = start; j <= end - 1; j++) {
    if (a[j] < pivot) {
      int tmp = a[j];
      a[j] = a[pivot_i];
      a[pivot_i] = tmp;
      pivot_i++;
    }
  }

  a[end] = a[pivot_i];
  a[pivot_i] = pivot;

  if (pivot_i == lthSmall) {
    return a[pivot_i];
  }

  if (pivot_i < lthSmall) {
    return quickFind(a, pivot_i + 1, end, lthSmall);
  }

  return quickFind(a, start, pivot_i - 1, lthSmall);
}

算法复杂度分析:

最好情况:

k > n

最坏情况:

(n-1)+(n-2)+(n-3)+...+1=n(n-1)/2

平均情况:

  • 不知怎么分析

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Learning Python, 5th Edition

Learning Python, 5th Edition

Mark Lutz / O'Reilly Media / 2013-7-6 / USD 64.99

If you want to write efficient, high-quality code that's easily integrated with other languages and tools, this hands-on book will help you be productive with Python quickly. Learning Python, Fifth Ed......一起来看看 《Learning Python, 5th Edition》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具