classKthLargest:def__init__(self,k:int,nums:List[int]):self.q=[]self.size=kfornuminnums:self.add(num)defadd(self,val:int)->int:heappush(self.q,val)iflen(self.q)>self.size:heappop(self.q)returnself.q[0]# Your KthLargest object will be instantiated and called as such:# obj = KthLargest(k, nums)# param_1 = obj.add(val)
classKthLargest{privatePriorityQueue<Integer>q;privateintsize;publicKthLargest(intk,int[]nums){q=newPriorityQueue<>(k);size=k;for(intnum:nums){add(num);}}publicintadd(intval){q.offer(val);if(q.size()>size){q.poll();}returnq.peek();}}/** * Your KthLargest object will be instantiated and called as such: * KthLargest obj = new KthLargest(k, nums); * int param_1 = obj.add(val); */
1 2 3 4 5 6 7 8 910111213141516171819202122
classKthLargest{public:priority_queue<int,vector<int>,greater<int>>q;intsize;KthLargest(intk,vector<int>&nums){size=k;for(intnum:nums)add(num);}intadd(intval){q.push(val);if(q.size()>size)q.pop();returnq.top();}};/** * Your KthLargest object will be instantiated and called as such: * KthLargest* obj = new KthLargest(k, nums); * int param_1 = obj->add(val); */
typeKthLargeststruct{h*IntHeapkint}funcConstructor(kint,nums[]int)KthLargest{h:=&IntHeap{}heap.Init(h)for_,v:=rangenums{heap.Push(h,v)}forh.Len()>k{heap.Pop(h)}returnKthLargest{h:h,k:k,}}func(this*KthLargest)Add(valint)int{heap.Push(this.h,val)forthis.h.Len()>this.k{heap.Pop(this.h)}returnthis.h.Top()}funcconnectSticks(sticks[]int)int{h:=IntHeap(sticks)heap.Init(&h)res:=0forh.Len()>1{val:=heap.Pop(&h).(int)val+=heap.Pop(&h).(int)res+=valheap.Push(&h,val)}returnres}typeIntHeap[]intfunc(hIntHeap)Len()int{returnlen(h)}func(hIntHeap)Less(i,jint)bool{returnh[i]<h[j]}func(hIntHeap)Swap(i,jint){h[i],h[j]=h[j],h[i]}func(h*IntHeap)Push(xany){*h=append(*h,x.(int))}func(h*IntHeap)Pop()any{old:=*hn:=len(old)x:=old[n-1]*h=old[0:n-1]returnx}func(h*IntHeap)Top()int{if(*h).Len()==0{return0}return(*h)[0]}/** * Your KthLargest object will be instantiated and called as such: * obj := Constructor(k, nums); * param_1 := obj.Add(val); */
importCollectionsclassKthLargest{privatevarh:Heap<Int>privatevarsize:Intinit(_k:Int,_nums:[Int]){h=Heap()size=kforxinnums{add(x)}}funcadd(_val:Int)->Int{h.insert(val)ifh.count>size{h.removeMin()}returnh.min!}}/** * Your KthLargest object will be instantiated and called as such: * let obj = KthLargest(k, nums) * let ret_1: Int = obj.add(val) */