Sort by

recency

|

422 Discussions

|

  • + 0 comments

    PYTHON3 SOLUTION:

    import sys
    import heapq
    
    class Heap:
        def __init__(self):
            self.heap = []
            self.counts = {}
        
        def insert(self, val):
            heapq.heappush(self.heap, val)
            self.counts[val] = self.counts.get(val, 0) + 1
        
        def delete(self, val):
            if self.counts.get(val, 0) > 0:
                self.counts[val] -= 1
        
        def minimum(self):
            while self.heap and self.counts.get(self.heap[0], 0) == 0:
                heapq.heappop(self.heap)
            return self.heap[0] if self.heap else None
    
    def main():
        q = int(sys.stdin.readline())
        heap = Heap()
        out = []
        for _ in range(q):
            parts = sys.stdin.readline().split()
            if parts[0] == "1":
                heap.insert(int(parts[1]))
            elif parts[0] == "2":
                heap.delete(int(parts[1]))
            else: 
                out.append(str(heap.minimum()))
        print("\n".join(out))
    
    if __name__ == "__main__":
        main()
    
  • + 0 comments

    I learned from Google AI, but I think I improved upon it :)

    import heapq

    myheap = [] heapq.heapify(myheap)

    Q = int(input()) valid = set()

    for _ in range(Q):

    command = [int(i) for i in input().split(' ')]
    
    if command[0] == 1:
        heapq.heappush(myheap, command[1])
        valid.add(command[1])
    elif command[0] == 2:
        valid.remove(command[1])
    elif command[0] == 3:
    
        while True:
            ans = myheap[0]
            if ans in valid:
                print(ans)
                break
            else:
                heapq.heappop(myheap)
    
  • + 0 comments

    Are we supposed to implement the heap ourselves or can we use Python's built-in heapq for the heap?

  • + 0 comments
    import java.io.*;
    import java.util.*;
    
    public class Solution {
        static PriorityQueue<Integer> minHeap = new PriorityQueue<>();
        public static void insert(int data){
            minHeap.add(data);
        }
        public static void delete(int data){
            minHeap.remove(data);
        }
        public static void printMin(){
            System.out.println(minHeap.peek());
        }
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
            for(int i = 0;i<n;i++){
                int action = sc.nextInt();
                if(action == 1){
                    int data = sc.nextInt();
                    insert(data);
                }
                else if(action == 2){
                    int data = sc.nextInt();
                    delete(data);
                }
                else if(action == 3){
                    printMin();
                }
            }
        }
    }
    
  • + 1 comment

    How is this easy lol