最小的k个数
来源:互联网 发布:835avcom永久域名 编辑:程序博客网 时间:2024/06/18 07:47
题目大致为:
输入n个整数,找出其中最小的k个数。
思路:
使用类似二叉查找树的形式实现,控制好树中的结点个数为k。
Java代码
package com.sun.jojo.datastructure;import java.util.Iterator;import java.util.TreeSet;/** * Author sunjiamin * Date 2017/8/15 16:10 * Describe : */public class MinK { public static void main(String args[]) { // 测试的例子 int array[] = { 4, 5, 1, 6, 2, 7, 3, 8 }; final int k = 4; TreeSet<Integer> set = getLeastNumbers(array, k); // 输出 Iterator<Integer> it = set.iterator(); System.out.println("最小的" + k + "个数为:"); while (it.hasNext()) { System.out.print(it.next() + "、"); } } /** * TreeSet 特性 如果元素具备自然顺序 的特性,那么就按照元素自然顺序的特性进行排序存储。 * 存放进的数据会自动排好序 * @param array * @param k * @return */ public static TreeSet<Integer> getLeastNumbers(int array[], int k) { TreeSet<Integer> set = new TreeSet<Integer>(); // 判断k和array的合法性 if (array == null || k <= 0) { return null; } for (int i = 0; i < array.length; i++) { if (set.size() < k) {// 如果TreeSet中的元素小于K个,则直接插入 set.add(array[i]); } else {// TreeSet中的元素大于K个 if (set.last() > array[i]) {// 最大的元素大于array[i] set.pollLast();// 移除 set.add(array[i]);// 加入新的 } } } return set; }}
结果:
最小的4个数为:1、2、3、4、
这里稍微看看TreeSet的add内部实现:
public V put(K key, V value) { Entry<K,V> t = root; if (t == null) { compare(key, key); // type (and possibly null) check root = new Entry<>(key, value, null); size = 1; modCount++; return null; } int cmp; Entry<K,V> parent; // split comparator and comparable paths Comparator<? super K> cpr = comparator; if (cpr != null) { do { parent = t; cmp = cpr.compare(key, t.key); if (cmp < 0) t = t.left; else if (cmp > 0) t = t.right; else return t.setValue(value); } while (t != null); } else { if (key == null) throw new NullPointerException(); @SuppressWarnings("unchecked") Comparable<? super K> k = (Comparable<? super K>) key; do { parent = t; cmp = k.compareTo(t.key); if (cmp < 0) t = t.left; else if (cmp > 0) t = t.right; else return t.setValue(value); } while (t != null); } Entry<K,V> e = new Entry<>(key, value, parent); if (cmp < 0) parent.left = e; else parent.right = e; fixAfterInsertion(e); size++; modCount++; return null; }
调用了cpr.compare(key, t.key);进行排序
阅读全文
0 0
- 最小的K个数
- 最小的K个数
- 最小的K个数
- 最小的k个数
- 最小的k个数
- 最小的k个数
- 最小的k个数
- 最小的k个数
- 最小的k个数
- 最小的K个数
- 最小的k个数
- 最小的K个数
- 最小的K个数
- 最小的K个数
- 最小的K个数
- 最小的K个数
- 最小的k个数
- 最小的k个数
- 安卓动画总结
- STM32系统时钟默认设置
- 无线通信常见的种类--随笔记
- 在Activity与Fragment中分别如何使用ButterKnife
- 未在本地计算机上注册“Microsoft.ACE.OLEDB.12.0”提供程序。
- 最小的k个数
- 微信小程序周报(第十一期)-极乐商店出品
- Ubuntu Server源码编译安装Apache2
- ViewPager竖向滑动
- SVN的安装与常用功能使用以及解决安装配置过程中的一些错误
- 配置本地git服务器(Windows)
- GDB十分钟教程
- Mysql 常用SQL语句集锦
- CoordinatorLayout与NestedScrollView嵌套RecyclerView滑动问题