Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Autosaved

...

https://leetcode.com/problems/super-ugly-number/

Code Block
languagego
func nthSuperUglyNumber(n int, primes []int) int {
    h_ := make(IntHeap, 0, n)
    h := &h_
    
    heap.Push(h, 1)
    
    num := -1
    exists := make(map[int]struct{})
    
    for i := 0; i < n; i++ {
        num = heap.Pop(h).(int)
        
        for _, p := range primes {
            nn := num * p
            if nn < num || nn > math.MaxInt32 {
                continue
            }
            
            if _, exist := exists[nn]; exist {
                continue
            }
            exists[nn] = struct{}{}
            
            heap.Push(h, nn)
        }
    }
    
    return num
}

// An IntHeap is a min-heap of ints.
type IntHeap []int

func (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *IntHeap) Push(x any) {
	// Push and Pop use pointer receivers because they modify the slice's length,
	// not just its contents.
	*h = append(*h, x.(int))
}

func (h *IntHeap) Pop() any {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

LC 1201. 丑数 III