zoukankan      html  css  js  c++  java
  • Leetcode 264. Ugly Number II

    264. Ugly Number II

    • Total Accepted: 35338
    • Total Submissions: 120258
    • Difficulty: Medium

    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.

    思路:动态规划。维持3条线路,uglynumnew=min(uglynum[k2]*2,uglynum[k3]*3,uglynum[k5]*3)(k2,k3,k5从0开始,uglynum[0]=1)。但要注意,可能会出现uglynumnew=uglynum[k2]*2=uglynum[k3]*3=uglynum[k5]*3的情况,此时,k2,k3,k5都要加1。

    代码:

     1 class Solution {
     2 public:
     3     int minnum(int a,int b,int c){
     4         return c<(min(a,b))?c:min(a,b);
     5     }
     6     int nthUglyNumber(int n) {
     7         vector<int> uglynum(1,1);
     8         int k2=0,k3=0,k5=0;
     9         while(uglynum.size()<n){
    10             int temp=minnum(uglynum[k2]*2,uglynum[k3]*3,uglynum[k5]*5);
    11             uglynum.push_back(temp);
    12             if(temp==uglynum[k2]*2){
    13                 k2++;
    14             }
    15             if(temp==uglynum[k3]*3){
    16                 k3++;
    17             }
    18             if(temp==uglynum[k5]*5){
    19                 k5++;
    20             }
    21         }
    22         return uglynum[n-1];
    23     }
    24 };
  • 相关阅读:
    不弹出提示直接关闭页面
    orcale表解锁
    序列化和反序列化
    js 实现post传参
    简易实现 instanceOf
    简易实现virtualdom
    react中setState同步、异步问题
    CMake Qt 配置 OpenCV
    VS执行时打开cmd
    VS2019+Qt5.15.2环境配置
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5675727.html
Copyright © 2011-2022 走看看