`
tang9140
  • 浏览: 34577 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

TopK问题探索-最小堆JAVA实现

 
阅读更多

TopK问题即如何从大量数据中找出前K个数(数之间可比较,较大的排前面)。

:这里使用数的概念,并不一定是数字,可以是任何对象,对象之间可以比较大小。


实际场景:比如搜索引擎找出得分最高的10篇文章,歌曲库中统计下载率最高的前10首歌等等。


下面探导有哪些实现方式:

方法一、将全部数据存放数组,然后对数组排序(大到小排),取出前K个数即可。

这种方式是最直接、最容易想到的方式。但由于是大量数据,存储和排序过程对内存、CPU资源消耗很大、效率低,不推荐使用。


方法二、从全部数据中取出K个数存入K大小的数组a中,对a按从小到大排序,则a[0]为最小值。然后依次取出其余数据,每取出一个数,都与a[0]比较,如果比a[0]小或相等,则取下一个数;反之,则丢弃a[0]的值,利用二分法找到其位置,然后该位置前的数组元素整体向前移动,如此反复读取,直到数据结尾。

这比方法一效率有很大提高,但如果K比较大时,整体移动也是比较耗时的

对于这种问题,效率比较高的解决方式是使用最小堆


最小堆(小根堆)是一种数据结构,它首先是一颗完全二叉树,并且,它所有父节点的值小于或等于两个子节点的值


最小堆的实际存储可以是数组,或者链表,用链表会更加灵活。


下面给出最小堆的一种JAVA实现方式(来自lucene源代码)


public abstract class PriorityQueue<T> {
  private int size;
  private final int maxSize;
  private final T[] heap;

  public PriorityQueue(int maxSize) {
    this(maxSize, true);
  }

  @SuppressWarnings("unchecked")
  public PriorityQueue(int maxSize, boolean prepopulate) {
    size = 0;
    int heapSize;
    if (0 == maxSize) {
      // We allocate 1 extra to avoid if statement in top()
      heapSize = 2;
    } else {
      if (maxSize > ArrayUtil.MAX_ARRAY_LENGTH) {
        throw new IllegalArgumentException("maxSize must be <= " + ArrayUtil.MAX_ARRAY_LENGTH + "; got: " + maxSize);
      } else {
        // NOTE: we add +1 because all access to heap is
        // 1-based not 0-based.  heap[0] is unused.
        heapSize = maxSize + 1;
      }
    }
    heap = (T[]) new Object[heapSize]; // T is unbounded type, so this unchecked cast works always
    this.maxSize = maxSize;
    
    if (prepopulate) {
      // If sentinel objects are supported, populate the queue with them
      T sentinel = getSentinelObject();
      if (sentinel != null) {
        heap[1] = sentinel;
        for (int i = 2; i < heap.length; i++) {
          heap[i] = getSentinelObject();
        }
        size = maxSize;
      }
    }
  }

  /** Determines the ordering of objects in this priority queue.  Subclasses
   *  must define this one method.
   *  @return <code>true</code> iff parameter <tt>a</tt> is less than parameter <tt>b</tt>.
   */
  protected abstract boolean lessThan(T a, T b);

  /**
   * This method can be overridden by extending classes to return a sentinel
   * object which will be used by the {@link PriorityQueue#PriorityQueue(int,boolean)} 
   * constructor to fill the queue, so that the code which uses that queue can always
   * assume it's full and only change the top without attempting to insert any new
   * object.<br>
   * 
   * Those sentinel values should always compare worse than any non-sentinel
   * value (i.e., {@link #lessThan} should always favor the
   * non-sentinel values).<br>
   * 
   * By default, this method returns false, which means the queue will not be
   * filled with sentinel values. Otherwise, the value returned will be used to
   * pre-populate the queue. Adds sentinel values to the queue.<br>
   * 
   * If this method is extended to return a non-null value, then the following
   * usage pattern is recommended:
   * 
   * <pre class="prettyprint">
   * // extends getSentinelObject() to return a non-null value.
   * PriorityQueue<MyObject> pq = new MyQueue<MyObject>(numHits);
   * // save the 'top' element, which is guaranteed to not be null.
   * MyObject pqTop = pq.top();
   * <...>
   * // now in order to add a new element, which is 'better' than top (after 
   * // you've verified it is better), it is as simple as:
   * pqTop.change().
   * pqTop = pq.updateTop();
   * </pre>
   * 
   * <b>NOTE:</b> if this method returns a non-null value, it will be called by
   * the {@link PriorityQueue#PriorityQueue(int,boolean)} constructor 
   * {@link #size()} times, relying on a new object to be returned and will not
   * check if it's null again. Therefore you should ensure any call to this
   * method creates a new instance and behaves consistently, e.g., it cannot
   * return null if it previously returned non-null.
   * 
   * @return the sentinel object to use to pre-populate the queue, or null if
   *         sentinel objects are not supported.
   */
  protected T getSentinelObject() {
    return null;
  }

  /**
   * Adds an Object to a PriorityQueue in log(size) time. If one tries to add
   * more objects than maxSize from initialize an
   * {@link ArrayIndexOutOfBoundsException} is thrown.
   * 
   * @return the new 'top' element in the queue.
   */
  public final T add(T element) {
    size++;
    heap[size] = element;
    upHeap();
    return heap[1];
  }

  /**
   * Adds an Object to a PriorityQueue in log(size) time.
   * It returns the object (if any) that was
   * dropped off the heap because it was full. This can be
   * the given parameter (in case it is smaller than the
   * full heap's minimum, and couldn't be added), or another
   * object that was previously the smallest value in the
   * heap and now has been replaced by a larger one, or null
   * if the queue wasn't yet full with maxSize elements.
   */
  public T insertWithOverflow(T element) {
    if (size < maxSize) {
      add(element);
      return null;
    } else if (size > 0 && !lessThan(element, heap[1])) {
      T ret = heap[1];
      heap[1] = element;
      updateTop();
      return ret;
    } else {
      return element;
    }
  }

  /** Returns the least element of the PriorityQueue in constant time. */
  public final T top() {
    // We don't need to check size here: if maxSize is 0,
    // then heap is length 2 array with both entries null.
    // If size is 0 then heap[1] is already null.
    return heap[1];
  }

  /** Removes and returns the least element of the PriorityQueue in log(size)
    time. */
  public final T pop() {
    if (size > 0) {
      T result = heap[1];       // save first value
      heap[1] = heap[size];     // move last to first
      heap[size] = null;        // permit GC of objects
      size--;
      downHeap();               // adjust heap
      return result;
    } else {
      return null;
    }
  }
  
  /**
   * Should be called when the Object at top changes values. Still log(n) worst
   * case, but it's at least twice as fast to
   * 
   * <pre class="prettyprint">
   * pq.top().change();
   * pq.updateTop();
   * </pre>
   * 
   * instead of
   * 
   * <pre class="prettyprint">
   * o = pq.pop();
   * o.change();
   * pq.push(o);
   * </pre>
   * 
   * @return the new 'top' element.
   */
  public final T updateTop() {
    downHeap();
    return heap[1];
  }

  /** Returns the number of elements currently stored in the PriorityQueue. */
  public final int size() {
    return size;
  }

  /** Removes all entries from the PriorityQueue. */
  public final void clear() {
    for (int i = 0; i <= size; i++) {
      heap[i] = null;
    }
    size = 0;
  }

  private final void upHeap() {
    int i = size;
    T node = heap[i];          // save bottom node
    int j = i >>> 1;
    while (j > 0 && lessThan(node, heap[j])) {
      heap[i] = heap[j];       // shift parents down
      i = j;
      j = j >>> 1;
    }
    heap[i] = node;            // install saved node
  }

  private final void downHeap() {
    int i = 1;
    T node = heap[i];          // save top node
    int j = i << 1;            // find smaller child
    int k = j + 1;
    if (k <= size && lessThan(heap[k], heap[j])) {
      j = k;
    }
    while (j <= size && lessThan(heap[j], node)) {
      heap[i] = heap[j];       // shift up child
      i = j;
      j = i << 1;
      k = j + 1;
      if (k <= size && lessThan(heap[k], heap[j])) {
        j = k;
      }
    }
    heap[i] = node;            // install saved node
  }
  
  /** This method returns the internal heap array as Object[].
   * @lucene.internal
   */
  protected final Object[] getHeapArray() {
    return (Object[]) heap;
  }
}

上面的抽象类封装了最小堆的一些基本操作,包括如何初始化最小堆、新增元素、弹出元素、调整根元素到适当位置等操作。在进行这些操作时,保证了最小堆的基本性质,即父结点的值小于或等于两个子结点值。

由于是抽象类,需要子类继续该类,并提供自己的lessThan方法的实现。

子类在使用时,需要先调用父类publicPriorityQueue(intmaxSize)或publicPriorityQueue(intmaxSize,booleanprepopulate)构造方法。


注:publicPriorityQueue(intmaxSize)实际是调用了后一个构造方法,参数prepopulate值为true


子类可重写protectedTgetSentinelObject()方法来决定是否要预填充堆,当该返回方法不为NULL时,且调用构造方法时参数prepopulate为true时,会预填充堆,即堆成员变量 T[] heap 数组的每个元素(除第一个元素外)赋上了非NULL值,且size赋值为maxSize的值,代表数组中已经有maxSize个元素;


注:size表示当前堆中元素实际个数,maxSize表示堆中可容纳的总元素,即容量。

另需要说明下,如果getSentinelObject()返回非NULL值,需要保证每次调用该方法,返回的都是new出来的新对象,而且该对象比其它任何对象的优先级都要低或相当,即lessThan(sentinelObject, otherObject)返回true


在初始化最小堆后,如果堆中未填充元素,可调用add方法新增元素到堆中;如果已经填充了元素,可调用top方法获取树最顶端元素,即根元素,改变根元素的一些值,当根元素改变时,需要子类调用public final T updateTop()方法来将根元素调整到适当位置。

注:由于最小堆的目的是存放前K个元素,在每次调用add方法前都要拿欲加入元素与根元素比较,如果小于或等于根元素,就不要执行add方法。同理,在欲改变根元素的一些值时,也是要进行比较的,只有当新的值比原来的值大时,才更改,并调用updateTop()方法


然后就涉及到如何取出堆中K个元素,这时就要循环调用pop()方法,每次调用都会弹出根元素,并存入数组或列表。由最小堆的性质可知,先弹出的元素肯定是要小于或等于后面的元素,这样就得到了排好序的前K个元素。


最小堆新增元素的时间复杂度为log(N)


版权声明:本文为博主原创文章,未经博主允许不得转载。

分享到:
评论

相关推荐

    taobao-sdk-java-auto-1.0.jar

    淘宝开放平台taobao-sdk-java-auto-1.0.jar 注意:com.taobao.top 文件路径

    taobao-sdk-java-auto_1479188381469-20190611-source.jar

    taobao-sdk-java-auto_1479188381469-20190611-source.jar 钉钉开发jar

    topk问题python k堆实现。。。。

    topk问题的Python实现,k-堆实现

    taobao-sdk-java.zip

    淘宝开放平台TOP,官方发布的最新java版SDK,2020年7月更新,如需要其他版本请留言,等待上传。

    最大(小)堆Java实现

    在Java中,最大堆通常用于优先队列的实现,比如在解决Top K问题、排序等问题时非常有效。 在Java中,我们可以通过自定义类来实现最大堆。下面将详细解释最大堆的实现过程,包括数据结构设计、插入、删除和筛选建立...

    Java实现TopK问题的方法

    下面将从两种方法来实现Java实现TopK问题:基于快排的TopK实现和堆排序实现TopK。 基于快排的TopK实现: 快排是最常见的排序算法之一,它可以在O(n log n)的时间复杂度内对数组进行排序。在快排的基础上,我们可以...

    淘宝sdk java 版

    淘宝开放平台api sdk java 版本 taobao-sdk-java-auto-*.jar

    dingtalk-sdk-java

    注意:此SDK包含原有TOP接口,原有TOP接口可以继续正常调用,没有影响。下面是使用SDK调用API的请求示例: JAVA: DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get"); ...

    taobao-sdk-java-auto_1479188381469-20191021.jar

    注意:此SDK包含原有TOP接口,原有TOP接口可以继续正常调用,没有影响。下面是使用SDK调用API的请求示例: JAVA: DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get"); ...

    Top-10-Java-Performance-Problems

    标题《Top-10-Java-Performance-Problems》和描述《专家总结》指出,文章将讨论Java性能问题中最常见的十个问题。这篇文章主要面向Java开发者,旨在帮助他们识别和解决影响Java应用性能的关键问题。 内容概要如下:...

    c-danlianbiao-jihe-jiaobingbu-topk-shi-CRUD

    TopK问题常见于数据分析中,它要求找到数据集中最大的K个元素。 例如,如果我们有一个销售记录表,可能需要找出销售额最高的前10个产品。这将涉及对所有产品销售额的排序,然后选取排名前10的项。在实际操作中,这...

    topK 问题的5种解决方案

    ### TopK 问题的五种解决方案 在计算机科学与数据处理领域中,TopK 问题是一种常见的需求场景,其核心任务是从一个数组或列表中找到最大的 K 个元素。这类问题广泛应用于各种场合,比如搜索引擎返回最相关的 K 条...

    一个简单的top-k实现

    在这个场景中,我们讨论的是一个用Java实现的简单Top-K算法。这个算法的目标是高效地找到一个数据集合中的前K个最大(或最小)的元素,而不需要对整个集合进行完整的排序。 在传统的排序方法中,如快速排序或归并...

    java实现TOP查询(java作业)

    这通常通过优先队列(如最小堆)实现,它能保持K个最大元素,并在新元素到来时自动更新。 3. **结果聚合**:节点间的局部结果需要聚合到一个中心节点,以得到全局的TOPK。有两种常见的聚合策略:一是采用网络传输,...

    Java实现堆并调整

    此外,堆也是解决Top-K问题和近似中位数查找的有效工具。通过理解和熟练运用堆的操作,可以显著提升算法的效率。 总的来说,`Heapest.java`和`HeapOperator.java`的代码可能包含了堆数据结构的创建、插入、删除以及...

    TOPK算法的Hash实现

    标题中的“TOPK算法的Hash实现”指的是使用哈希数据结构来解决找出数据集中最大或最小的K个元素的问题。这种算法通常用于大数据处理和实时分析中,因为哈希表可以提供快速的查找和更新操作。 TOPK算法的核心是通过...

    C语言TOP-K问题(从一堆数据中找出最大的k个数或者最小的k个数)

    在解决TOP-K问题时,我们通常会用到最大堆或最小堆。 首先,让我们了解堆的基本操作: 1. **插入元素 (Heapify Up)**:当新元素插入堆时,需要确保它与它的父节点保持堆属性。如果新元素比父节点大(大顶堆)或小...

    淘宝SDK(java)

    3. **taobao-sdk-java-online_standard-20140408.jar**:这是主SDK的jar文件,包含了所有必要的类和方法,供开发者在项目中引入并使用。开发者将此文件添加到项目的类路径中,就可以开始调用淘宝API了。 4. **...

    Solaris系统上top工具top-3.6.1-sol10-x86-local

    3、看到了top-3.6-sol9-sparc-local这个文件,千万别以为完活了呢,直接执行这个文件会报"top-3.6-sol9-sparc-local: SMCtop: 没找到"等等一堆错的。这一步该做pkgtrans操作了 # pkgadd -d top-3.6-sol9-sparc-...

    TopK问题(大顶堆 + 快排)

    TopK问题(大顶堆 + 快排)

Global site tag (gtag.js) - Google Analytics