Sword refers to Offer 49. Ugly numbers (implemented in java) --LeetCode

Article Directory

topic:

We call numbers that only contain prime factors 2, 3, and 5 as Ugly Numbers. Find the nth ugly number in ascending order.

Example:

输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。

Description:

  • 1 is an ugly number.
  • n does not exceed 1690.

Note: This question is the same as the main site 264 question: https://leetcode-cn.com/problems/ugly-number-ii/

Solution 1: heap

/**
 * 思路:
 * 丑数:从1开始,当前的数*235,插入堆中,之后删除堆顶元素加入到result中
 * 在用堆顶元素*235,将新的丑数加入到堆中,并用set集合去重。循环这个过程
 */
    public int nthUglyNumber(int n) {
    
    
        PriorityQueue<Long> heap = new PriorityQueue<>();
        heap.add(1L);
        long[] res = new long[n + 1];
        int[] primes={
    
    2,3,5};
        HashSet<Long> set = new HashSet<>();
        int index=1;
        while (!heap.isEmpty()) {
    
    
            Long remove = heap.remove();
            for (int prime : primes) {
    
    
                long uglyNum = remove * prime;
                if (!set.contains(uglyNum)) {
    
    
                    set.add(uglyNum);
                    heap.add(uglyNum);
                }
            }
            res[index++] = remove;
            if (index == res.length) return (int)res[n];
        }
        return (int)res[n];
    }

Time complexity: On

Space complexity: On
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_38783664/article/details/112771293