Large and small roof top heap heap -java

A large stack and a small roof top of the heap principle

1, large 顶堆

  • Keyword root (also called the top of the heap) is a pile of all the nodes in the largest of keywords, called the big top heap. Large root heap requires both root keywords than or equal to the value of the left subtree keywords, and keyword values ​​greater than or equal to the right subtree.

2, the top of a small heap

  • Root key (also known as top of the stack) are all nodes pile least of keywords, called small stack top. Small heap root root requirements both keyword or less left subtree key value, and less than or equal to the key value of the right subtree.

3, large and small stack top stack top comparison chart

4, pushing large and small achieve top of the heap

public class MaxHeap {
    public static void main(String[] args) {
        //原始数组内容
        int i,size,data[]={0,5,6,10,8,3,2,19,9,11};

        size=data.length;

        System.out.print("原始数组:");

        for(i=1;i<size;i++)
            System.out.print("["+data[i]+"] ");

        System.out.println("");
        //建立堆积树
        MaxHeap.heap(data,size);
    }
    public static void heap(int data[] ,int size)
    {
        int i,j,tmp;
        //建立堆积树节点
        for(i=(size/2);i>0;i--)
            MaxHeap.ad_heap(data,i,size-1);
        System.out.print("\n堆积内容:");
        //原始堆积树内容
        for(i=1;i<size;i++)
            System.out.print("["+data[i]+"] ");
    }

    public static void ad_heap(int data[],int i,int size){
        int j,tmp,post;
        j=2*i;
        tmp=data[i];
        post=0;
        while(j<=size && post==0)
        {
            if(j<size)
            {
                //小顶堆的比较           
                //if(data[j]>data[j+1])  
                //找出两个子节点最大值
                if(data[j]<data[j+1])  
                    j++;
            }
            //小顶堆的比较
            //if(tmp<=data[j])   
            //若树根较大,结束比较过程
            if(tmp>=data[j])    {
                post=1;  
            } else {
                //若树根较小,则继续比较,这里将最大子节点赋值给父节点
                data[j/2]=data[j];     
                j=2*j;
            }
        }
        //指定树根为父节点
        data[j/2]=tmp;                
    }
}
复制代码

Second, the small heap of top applications

1, seeking the maximum number k

  • 1, seeking the maximum number 1000000000 10 before the number, often only a small top of the stack constructed of 10 elements, if less than the top of the stack, no treatment; if larger than the top of the stack, replacing the top of the stack, followed by sink into place. See detailed public explanation number: Code farming Wealth
  • 2, select the maximum number K
public class findTopK {
    //用PriorityQueue默认是自然顺序排序,要选择最大的k个数,构造小顶堆,每次取数组中剩余数与堆顶的元素进行比较,如果新数比堆顶元素大,则删除堆顶元素,并添加这个新数到堆中。
    //找出前k个最大数,采用小顶堆实现
    public static int[] findKMax(int[] nums, int k) {
        //队列默认自然顺序排列,小顶堆,不必重写compare
        PriorityQueue<Integer> pq = new PriorityQueue<>(k);
        
        for (int num : nums) {
            if (pq.size() < k) {
                pq.offer(num);
                //如果堆顶元素 < 新数,则删除堆顶,加入新数入堆
            } else if (pq.peek() < num) {
                pq.poll();
                pq.offer(num);
            }
        }
        
        int[] result = new int[k];
        for (int i = 0; i < k&&!pq.isEmpty(); i++) {
            result[i] = pq.poll();
        }
        return result;
    }

 public static void main(String[] args) {
        int[]arr=new int[]{1, 6, 2, 3, 5, 4, 8, 7, 9};
        System.out.println(Arrays.toString(findKMax( arr,5)));
    }
}
复制代码

2, the array of K-th largest element

 // 小顶堆
  PriorityQueue<Integer> pq = new PriorityQueue<>();
    for (int val : nums) {
        pq.add(val);
        // 维护堆的大小为 K
        if (pq.size() > k) {
        //弹出最顶端的数,并删除
             pq.poll();
        }
    }
    //取最顶端的数
    return pq.peek();
    }
复制代码

Third, the application heap big top

  • PriorityQueue can be achieved by passing a large stack top custom function compara

1, to select the smallest number K large stack top, each taking the number of elements in the array and the remaining top of the stack are compared, if the new top of the stack is smaller than the number of elements, then deleting the top of the stack of elements, and to add this new number heap.

public static int[] findKMin(int[] nums,int k ){
        PriorityQueue<Integer> pq = new PriorityQueue<>(k, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        });

        for (int num:nums){
            if (pq.size() <k){
                pq.offer(num);
                //如果堆顶元素 > 新数,则删除堆顶,加入新数入堆
            }else if(pq.peek() > num){
                pq.poll();
                pq.offer(num);

            }
        }
        int[] result = new int[k];
        for (int i = 0;i<k&&!pq.isEmpty();i++){
            result[i] = pq.poll();
        }
        return result;
    }

    public static void main(String[] args) {
        int[]arr=new int[]{1, 6, 2, 3, 5, 4, 8, 7, 9};
        System.out.println(Arrays.toString(findKMin( arr,5)));
    }

复制代码

2, the array of K-th smallest element

   public static int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> pq = new PriorityQueue<>(k, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        });

        for (int val : nums) {
            pq.add(val);
            // 维护堆的大小为 K
            if (pq.size() > k) {
                pq.poll();
            }
        }
        return pq.peek();
    }
复制代码

Reproduced in: https: //juejin.im/post/5d0654fd51882554d63127d1

Guess you like

Origin blog.csdn.net/weixin_34206899/article/details/93166272