题解 | #【模板】堆#

【模板】堆

https://www.nowcoder.com/practice/13f61c8c92404f5ea5d6fa4c692869fb

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        final String push = "push",pop = "pop",tio = "top";
        Scanner scanner = new Scanner(System.in);
        //输入次数
        int num = scanner.nextInt();
        Head head = new Head(num);
        scanner.nextLine();
        for(int i=0;i<num;i++){
            String str = scanner.nextLine();
            String[] split = str.split("\\s+");
            if("push".equals(split[0])){
                head.push(Integer.parseInt(split[1]));
            }else if("top".equals(split[0])){
                head.top();
            }else if("pop".equals(split[0])){
                head.pop();
            }
        }
    }
}
class Head{
    private int[] array;
    private int length;

    public Head(int n){
        array = new int[n];
        length = 0;
    }

    public void push(int value){
        array[length++] = value;
        for(int i = length / 2 - 1;i>=0;i = (i-1)/2){
            adjustHeap(i);
            if(i==0){
                break;
            }
        }
    }
    
    public void top(){
        if(length == 0){
            System.out.println("empty");
            return;
        }
        System.out.println(array[0]);
    }

    public void pop(){
        if(length == 0){
            System.out.println("empty");
            return;
        }
        System.out.println(array[0]);
        array[0] = array[length - 1];
        length--;
        adjustHeap(0);
    }

    private void adjustHeap(int i){
        int temp = array[i];
        for(int k = 2 * i + 1;k<length;k=k*2+1){
            if(k+1<length && array[k+1] > array[k]){
                k++;
            }
            if(array[k] > temp){
                array[i] = array[k];
                i = k;
            }else{
                break;
            }
        }
        array[i] = temp;
    }
}

全部评论

相关推荐

joe2333:怀念以前大家拿华为当保底的日子
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务