zoukankan      html  css  js  c++  java
  • 264. 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

    Example:

    Input: n = 10
    Output: 12
    Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

    Note:  

    1. 1 is typically treated as an ugly number.
    2. n does not exceed 1690.
     

    Approach #1: C++. generate all ugly numbers then sort.

    class Solution {
    public:
        int nthUglyNumber(int n) {
            vector<int> temp;
            for (long i = 1; i < INT_MAX; i = i*2) {
                for (long j = i; j < INT_MAX; j = j*3) {
                    for (long k = j; k < INT_MAX; k = k*5) {
                        temp.push_back(k);
                    }
                }
            }
            sort(temp.begin(), temp.end());
            return temp[n-1];
        }
    };
    

      

    Approach #2: Java. [order generate]

    class Solution {
        public int nthUglyNumber(int n) {
            List<Integer> nums = new ArrayList<Integer>();
            nums.add(1);
            int i1 = 0;
            int i2 = 0;
            int i3 = 0;
            while (nums.size() < n) {     
                int ant = Math.min(nums.get(i1) * 2, Math.min(nums.get(i2) * 3, nums.get(i3) * 5));
                nums.add(ant);
                if (nums.get(i1) * 2 == ant) i1++;
                if (nums.get(i2) * 3 == ant) i2++;
                if (nums.get(i3) * 5 == ant) i3++;
            }
            
            return nums.get(n-1);
        }
    }
    

      

    Approach #3: Python.

    class Solution(object):
        def nthUglyNumber(self, n):
            """
            :type n: int
            :rtype: int
            """
            ugly = [1]
            i2 = i3 = i5 = 0
            
            while len(ugly) < n:
                while ugly[i2]*2 <= ugly[-1]: i2 += 1
                while ugly[i3]*3 <= ugly[-1]: i3 += 1
                while ugly[i5]*5 <= ugly[-1]: i5 += 1
                ugly.append(min(ugly[i2]*2, ugly[i3]*3, ugly[i5]*5))
            
            return ugly[-1]
    

      

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    12月11日,12月12日登陆注册页面的进度
    11月28日进度
    11.23JavaScript学习打卡
    11.21,11.22HTML笔记整理
    11.19打卡,HTML学习笔记整理
    select into from 与 insert into select 区别
    解决Cookie乱码
    COOKIE传值
    实现鼠标穿透窗体
    监视鼠标点击了左键还是右键
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10133914.html
Copyright © 2011-2022 走看看