Skip to content

Commit

Permalink
add sol
Browse files Browse the repository at this point in the history
  • Loading branch information
ductnn committed Dec 22, 2023
1 parent d7cd9ce commit 8544cd5
Show file tree
Hide file tree
Showing 2 changed files with 93 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -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))
}
Original file line number Diff line number Diff line change
@@ -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);
*/

0 comments on commit 8544cd5

Please sign in to comment.