diff --git a/leetcode/leetcode75/HeapAndPriorityQueue/215.KthLargestElementinanArray/sol.go b/leetcode/leetcode75/HeapAndPriorityQueue/215.KthLargestElementinanArray/sol.go new file mode 100644 index 0000000..682d8eb --- /dev/null +++ b/leetcode/leetcode75/HeapAndPriorityQueue/215.KthLargestElementinanArray/sol.go @@ -0,0 +1,59 @@ +// https://leetcode.com/problems/kth-largest-element-in-an-array + +package main + +import ( + "container/heap" + "fmt" + "sort" +) + +// with sorting +func findKthLargest(nums []int, k int) int { + sort.Ints(nums) + return nums[len(nums)-k] +} + +// without sorting +type Heap []int + +func (h Heap) Len() int { + return len(h) +} + +func (h Heap) Less(i, j int) bool { + return h[i] <= h[j] +} + +func (h *Heap) Swap(i, j int) { + (*h)[i], (*h)[j] = (*h)[j], (*h)[i] +} + +func (h *Heap) Push(x interface{}) { + *h = append(*h, x.(int)) +} + +func (h *Heap) Pop() interface{} { + old := *h + n := len(old) + x := old[n-1] + *h = old[:n-1] + return x +} + +func findKthLargest1(nums []int, k int) int { + tmp := Heap(nums) + h := &tmp + heap.Init(h) + for len(*h) > k { + heap.Pop(h) + } + return (*h)[0] +} + +func main() { + nums := []int{3, 2, 3, 1, 2, 4, 5, 5, 6} + k := 4 + + fmt.Println(findKthLargest1(nums, k)) +} diff --git a/leetcode/leetcode75/HeapAndPriorityQueue/2336.SmallestNumberinInfiniteSet/smallestNumberinInfiniteSet.go b/leetcode/leetcode75/HeapAndPriorityQueue/2336.SmallestNumberinInfiniteSet/smallestNumberinInfiniteSet.go new file mode 100644 index 0000000..28ce4d3 --- /dev/null +++ b/leetcode/leetcode75/HeapAndPriorityQueue/2336.SmallestNumberinInfiniteSet/smallestNumberinInfiniteSet.go @@ -0,0 +1,34 @@ +// https://leetcode.com/problems/smallest-number-in-infinite-set + +package main + +import "github.com/emirpasic/gods/maps/treemap" + +type SmallestInfiniteSet struct { + s *treemap.Map +} + +func Constructor() SmallestInfiniteSet { + s := treemap.NewWithIntComparator() + for i := 1; i <= 1000; i++ { + s.Put(i, nil) + } + return SmallestInfiniteSet{s} +} + +func (this *SmallestInfiniteSet) PopSmallest() int { + x, _ := this.s.Min() + this.s.Remove(x.(int)) + return x.(int) +} + +func (this *SmallestInfiniteSet) AddBack(num int) { + this.s.Put(num, nil) +} + +/** + * Your SmallestInfiniteSet object will be instantiated and called as such: + * obj := Constructor(); + * param_1 := obj.PopSmallest(); + * obj.AddBack(num); + */