how to determine if the kth largest element of the heap is greater than x

后端 未结 2 822
清歌不尽
清歌不尽 2020-12-02 15:12

Consider a binary heap containing n numbers (the root stores the greatest number). You are given a positive integer k < n and a number x. You have to determine whether th

2条回答
  •  日久生厌
    2020-12-02 15:29

    public class KSmallest2 {
    
    private MinPQ minHeap;
    private int x;
    private int k;
    private int count = 0;
    
    public KSmallest2(String filename, int x, int k) {
        this.x = x;
        this.k = k;
        minHeap = new MinPQ<>();
        try {
            Scanner in = new Scanner(new File(filename));
            while (in.hasNext()) {
                minHeap.insert(in.nextInt());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    
    public boolean check(int index) {
    
        if (index > minHeap.size()) {
            return false;
        }
    
        if (minHeap.getByIndex(index) < x) {
            count++;
            if (count >= k) {
                return true;
            }
    
            return  check(2 * index) ||
                    check(2 * index + 1);
        }
    
        return false;
    }
    
    
    
    public static void main(String[] args) {
        KSmallest2 ks = new KSmallest2("src/main/resources/minheap.txt", 18, 5);
        System.out.println(ks.minHeap);
    
        System.out.println(ks.check(1));
    }
    

    }

提交回复
热议问题