博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
最小的 K 个数
阅读量:4212 次
发布时间:2019-05-26

本文共 1183 字,大约阅读时间需要 3 分钟。

解题思路

快速选择

  • 复杂度:O(N) + O(1)
  • 只有当允许修改数组元素时才可以使用

快速排序的 partition() 方法,会返回一个整数 j 使得 a[l..j-1] 小于等于 a[j],且 a[j+1..h] 大于等于 a[j],此时 a[j] 就是数组的第 j 大元素。可以利用这个特性找出数组的第 K 个元素,这种找第 K 个元素的算法称为快速选择算法。

 

public ArrayList
GetLeastNumbers_Solution(int[] nums, int k) { ArrayList
ret = new ArrayList<>(); if (k > nums.length || k <= 0) return ret; findKthSmallest(nums, k - 1); /* findKthSmallest 会改变数组,使得前 k 个数都是最小的 k 个数 */ for (int i = 0; i < k; i++) ret.add(nums[i]); return ret;}public void findKthSmallest(int[] nums, int k) { int l = 0, h = nums.length - 1; while (l < h) { int j = partition(nums, l, h); if (j == k) break; if (j > k) h = j - 1; else l = j + 1; }}private int partition(int[] nums, int l, int h) { int p = nums[l]; /* 切分元素 */ int i = l, j = h + 1; while (true) { while (i != h && nums[++i] < p) ; while (j != l && nums[--j] > p) ; if (i >= j) break; swap(nums, i, j); } swap(nums, l, j); return j;}private void swap(int[] nums, int i, int j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t;}

 

转载地址:http://bckmi.baihongyu.com/

你可能感兴趣的文章
《redis in action》key的自动过期
查看>>
《redis in action》redis持久化简介
查看>>
《redis in action》redis快照
查看>>
《redis in action》Redis aof持久化
查看>>
《redis in action》开启aof日志
查看>>
CS224N研究热点2_Linear Algebraic Structure of Word Senses, with Applications to Polysemy(对于一词多义的向量表示研究)
查看>>
Java编程中,什么数据类型适合用来表示价格?
查看>>
ssh出错:sign_and_send_pubkey: signing failed: agent refused operation
查看>>
Zookeeper启动成功,但无法查看status
查看>>
OCFS2+ASM 的RAC安装文档
查看>>
Oracle RAC Failover 详解
查看>>
批处理 自动修改 IP 地址
查看>>
Oracle RAC LoadBalance
查看>>
v$sql,v$sqlarea,v$sqltext 和 v$sql_plan 说明
查看>>
ORA-31623 When Submitting a Datapump Job [ID 308388.1]
查看>>
Oracle SYSAUX 表空间 说明
查看>>
RAC 安装patch 后启动实例 报错 ORA-00439 feature not enabled- Real Application Clusters 解决方法
查看>>
On RAC, expdp Removes the Service Name [ID 1269319.1]
查看>>
Important Changes to Oracle Database Patch Sets Starting With 11.2.0.2 [ID 1189783.1]
查看>>
Oracle RAC 平台下 Patch 安装与卸载 步骤
查看>>