zoukankan      html  css  js  c++  java
  • 【LeetCode】264. Ugly Number II

    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.

    Show Hint 

      Credits:
      Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

      思路:所有的ugly number都是由1开始,乘以2/3/5生成的。

      只要将这些生成的数排序即可获得,自动排序可以使用set

      这样每次取出的第一个元素就是最小元素,由此再继续生成新的ugly number.

      class Solution {
      public:
          int nthUglyNumber(int n) {
              set<long long> order;
              order.insert(1);
              int count = 0;
              long long curmin = 0;
              while(count < n)
              {
                  curmin = *(order.begin());
                  order.erase(order.begin());
                  order.insert(curmin * 2);
                  order.insert(curmin * 3);
                  order.insert(curmin * 5);
                  count ++;
              }
              return (int)curmin;
          }
      };

    1. 相关阅读:
      JS
      JS
      JS
      CSS
      CSS
      CSS
      NPOI导出自动换行效果
      Httpcookie的简单应用
      前台JS设置Cookies后台读取刚设置的Cookies
      SQL SERVER 如何调试存储过程
    2. 原文地址:https://www.cnblogs.com/ganganloveu/p/4749993.html
    Copyright © 2011-2022 走看看