zoukankan      html  css  js  c++  java
  • leetcode@ [263/264] Ugly Numbers & Ugly Number II

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

    Write a program to check whether a given number is an ugly number.

    Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.

    Note that 1 is typically treated as an ugly number.

    class Solution {
    public:
        bool isUgly(int num) {
            if(num <= 0) return false;
            if(num == 1) return true;
            
            while(num%2 == 0){
                num/=2;
                if(num == 1) return true;
            }
            while(num%3 == 0){
                num/=3;
                if(num == 1) return true;
            } 
            while(num%5 == 0){
                num/=5;
                if(num == 1) return true;
            }
            return false;
        }
    };
    leetcode 263: Ugly Numbers

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

    Write a program to find the n-th ugly number.

    Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

    Note that 1 is typically treated as an ugly number.

    Hint:

    1. The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones.
    2. An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.
    3. The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3
    class Solution {
    public:
        int nthUglyNumber(int n) {
            if(n <= 6) return n;
            
            vector<long long> dp(n+1, 0);
            for(int i=1;i<=6;++i) dp[i] = i;
            
            for(int i=7;i<=n;++i) {
                long long Min = numeric_limits<long long>::max();
                for(int pre=1;pre<=i-1;++pre) {
                    if(dp[pre]*2 > dp[i-1]) {Min = min(Min, dp[pre] * 2); continue;}
                    else if(dp[pre] * 3 > dp[i-1]) {Min = min(Min, dp[pre] * 3);continue;}
                    else if(dp[pre] * 5 > dp[i-1]) Min = min(Min, dp[pre] * 5);
                }
                dp[i] = Min;
            }
            
            return dp[n];
        }
    };
    leetcode 264: Ugly Numbers II
  • 相关阅读:
    如何对抗硬件断点--- 调试寄存器
    学会破解要十招
    Ollydbg 中断方法浅探
    脱壳经验(二)--如何优化
    jquery 选择器,模糊匹配
    CSS实现内容超过长度后以省略号显示
    微信内置浏览器浏览H5页面弹出的键盘遮盖文本框的解决办法
    Exif.js获取图片的详细信息(苹果手机移动端上传图片旋转90度)
    jquery中的$("#id")与document.getElementById("id")的区别
    CentOS7 安装lua环境(我是在mysql读写分离用的)
  • 原文地址:https://www.cnblogs.com/fu11211129/p/5000455.html
Copyright © 2011-2022 走看看