• [LeetCode] 264. Ugly Number II Java


    题目:

    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, and n does not exceed 1690.

    题意及分析:ugly是只能被2,3,5整除的数,要求求出第n个ugly数。通过观察可以发现:当前的数是由前面已存在的数乘以2/3/5,所以我们对每一个存在的数乘以2,3,5然后去重排序就可以产生后续的ugly数。用一个sortSet维护即可。

    代码:

    public class Solution {
        public int nthUglyNumber(int n) {
            if(n<=0) return 0;
    		SortedSet<Long> sortedSet=new TreeSet<>();    //这里使用long,因为一个int*2或者3,5之后可能超出int
            sortedSet.add((long)1);
            long res=sortedSet.first();
            
            for(int i=0;i<n-1;i++){
            	res=sortedSet.first();
            	sortedSet.add(res*2);
            	sortedSet.add(res*3);
            	sortedSet.add(res*5);
            	sortedSet.remove(res);
            }
            return (int)((long)sortedSet.first());
        }
    }
    

      

  • 相关阅读:
    Java平台调用Python平台已有算法(附源码及解析)
    java截取避免空字符丢失
    Java集合对象比对
    idea中的beautiful插件-自动生成对象set方法
    idea下maven命令打包不同配置
    提纲
    标记语言入门
    react入门
    深入理解React、Redux
    css伪类 伪元素
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7048675.html
Copyright © 2020-2023  润新知