Java实现-丑数2

来源:互联网 发布:中国检察网络培训学校 编辑:程序博客网 时间:2024/06/05 21:41

设计一个算法,找出只含素因子235 的第 n 大的数。

符合条件的数如:1, 2, 3, 4, 5, 6, 8, 9, 10, 12...

 注意事项

我们可以认为1也是一个丑数

样例

如果n = 9, 返回 10

挑战 

要求时间复杂度为O(nlogn)或者O(n)

class Solution {    /**     * @param n an integer     * @return the nth prime number as description.     */    public int nthUglyNumber(int n) {        // Write your code here        List<Integer> uglys=new ArrayList<Integer>();uglys.add(1);int p2=0;int p3=0;int p5=0;for(int i=1;i<n;i++){int lastNumber=uglys.get(uglys.size()-1);while(uglys.get(p2)*2<=lastNumber){p2++;}while(uglys.get(p3)*3<=lastNumber){p3++;}while(uglys.get(p5)*5<=lastNumber){p5++;}int newValue=Math.min(uglys.get(p2)*2, Math.min(uglys.get(p3)*3, uglys.get(p5)*5));uglys.add(newValue);}return uglys.get(uglys.size()-1);    }};


原创粉丝点击