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 };
  • 相关阅读:
    互联网架构 高可用和高并发 (转)
    mysql数据库索引
    SQL小结
    limit小结
    JDK8 元空间
    OpenStack基础知识
    shell 发送所有内容到会话
    通过word给博客园发布文章教程
    centos7.4安装过程
    Zabbix 调整告警发送的内容格式
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5675727.html
Copyright © 2011-2022 走看看