LeetCode_Heap_264. Ugly Number II 丑数 II【堆,大数处理】【C++/java】【中等】

目录

一,题目描述

英文描述

中文描述

示例与说明

二,解题思路

三,AC代码

C++

Java

四,解题过程

第一博


一,题目描述

英文描述

An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.

Given an integer n, return the nth ugly number.

中文描述

给你一个整数 n ,请你找出并返回第 n丑数

丑数 就是只包含质因数 23 和/或 5 的正整数。

示例与说明

 

提示:

  • 1 <= n <= 1690

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ugly-number-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二,解题思路

之前做过一个类似于动态规划的方法(后来才知道这是动态规划)。

  • 给每个因数设置一个指针,比如indexOf2、indexOf3等,这个指针指向生成的丑数数组中对应位置,每次循环时,选出ans[indexOf2]*2、ans[indexOf3]等等中的最小的值,将这个值添加到ans数组中,并将对应的indexOfn指针后移一位。
  • 若出现多个值相同,则他们的指针均后移一位。

这里采用堆的方法。

  • 设计小根堆。最外层循环设置n,控制每次取出堆一个最小的丑数。
  • 将取出的丑数分别乘上三个因子并存入堆中,继续下一次循环。

三,AC代码

C++

class Solution {
public:
    struct cmp {
        bool operator()(long a, long b) {
            return a > b;
        }
    };
    int nthUglyNumber(int n) {
        int factors[] = {2, 3, 5};
        priority_queue<long, vector<long>, cmp> heap;
        unordered_set<long> record;
        heap.push(1);
        while (--n) {
            long cur = heap.top();
            heap.pop();
            for (auto f : factors) {
                long next = cur * f;
                if (record.find(next) == record.end()) {
                    heap.push(next);
                    record.insert(next);
                }
            }
        }
        return int(heap.top());
    }
};

Java

class Solution {
    public int nthUglyNumber(int n) {
        Set<Long> record = new HashSet<Long>();
        int[] factors = {2, 3, 5};
        PriorityQueue<Long> queue = new PriorityQueue<Long>(new Comparator<Long>(){
            public int compare(Long a, Long b) {
                return Long.compare(a, b);// !!!这里不能直接相减
            }
        });
        // PriorityQueue<Long> queue = new PriorityQueue<Long>((a, b) -> (Long.compare(a, b)));
        queue.offer(1L);
        int ans = 0;
        while (n-- > 0) {
            long cur = queue.peek();
            ans = (int) cur;
            queue.poll();
            for (int f : factors) {
                long next = cur * f;
                if (record.add(next)) {
                    queue.offer(next);
                }
            }
        }
        return ans;
    }
}

四,解题过程

第一博

java版的搞了好长时间,最后发现是大数的处理问题。比较器中Long类型的数据最好不要直接相减去比较,而是通过Long.compare()获得结果。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值