栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

LeetCode

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode

目录

一,题目描述

英文描述

中文描述

示例与说明

二,解题思路

三,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 个 丑数 。

丑数 就是只包含质因数 2、3 和/或 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, cmp> heap;
        unordered_set 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 record = new HashSet();
        int[] factors = {2, 3, 5};
        PriorityQueue queue = new PriorityQueue(new Comparator(){
            public int compare(Long a, Long b) {
                return Long.compare(a, b);// !!!这里不能直接相减
            }
        });
        // PriorityQueue queue = new PriorityQueue((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()获得结果。

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/456761.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号