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 };
  • 相关阅读:
    域名和dns
    Oracle版本区别及版本选择!
    并发
    URL和URI的区别??
    sshpass免密码(免交互)连接
    python之路 目录
    awk sed 总结
    aiohttp使用
    Mac破解软件 “XXX”意外退出 奔溃解决方法
    我的Mac中毒了,病毒居然叫做MacPerformance
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5675727.html
Copyright © 2011-2022 走看看