zoukankan      html  css  js  c++  java
  • LeetCode: Ugly Number II

    题目链接https://leetcode.com/problems/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.

    题目意思:找第n个丑数

    思路按顺序省城丑数,当前要生成的丑数肯定是前面某一个丑数乘以2,3或5。但并不须要把当前每一个丑数都乘以2,3和5。由于已生成的丑数在数组是按顺序存放的。

    对于乘以2而言。肯定存在某一个丑数t2,使得排在它之前的每一个丑数乘以2得到的结果都会小于已有最大丑数,在它之后的每一个丑数乘以2得到的结果都会大于当前最大丑数。我们仅仅须要记下这个丑数的位置,同一时候每次生成新的丑数时去更新这个t2。

    对于3和5。相同存在t3和t5。

    AC代码

    public class Solution {
        public int MinT(int t1, int t2, int t3) {
    		int min = t1 < t2 ? t1 : t2;
    		return min < t3 ?

    min : t3; } public int nthUglyNumber(int n) { int[] uglyNums = new int[n]; int next = 1; int i=0, j=0, k=0; //分别记录t2,t3,t5当前位置 uglyNums[0] = 1; while(next < n) { int min = MinT(uglyNums[i]*2, uglyNums[j]*3, uglyNums[k]*5); uglyNums[next] = min; if(uglyNums[i]*2 == min) i++; if(uglyNums[j]*3 == min) j++; if(uglyNums[k]*5 <= min) k++; next++; } return uglyNums[n-1]; } }


     

  • 相关阅读:
    【数组】Unique Paths II
    【数组】Unique Paths
    【数组】word search
    购物网站布局实战
    Javascript显示和隐式类型转换
    JS检测数据类型
    从setTimeout谈js运行机制
    0.1 + 0.2 = 0.30000000000000004怎样理解
    (译)详解javascript立即执行函数表达式(IIFE)
    Redis
  • 原文地址:https://www.cnblogs.com/gccbuaa/p/6872948.html
Copyright © 2011-2022 走看看