[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