[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());
    }
}

 

  

 

转载于:https://www.cnblogs.com/271934Liao/p/7048675.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值