算法 - 查找第K大数字

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

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

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

  • 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

平均情况:

  • 不知怎么分析

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

查看所有标签

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

Pragmatic Thinking and Learning

Pragmatic Thinking and Learning

Andy Hunt / The Pragmatic Bookshelf / 2008 / USD 34.95

In this title: together we'll journey together through bits of cognitive and neuroscience, learning and behavioral theory; you'll discover some surprising aspects of how our brains work; and, see how ......一起来看看 《Pragmatic Thinking and Learning》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具