码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode 264] Ugly Number II

时间:2015-09-02 00:41:00      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:leetcode   math   

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.

  1. An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.
维护一个ordered data structure to store ugly number, every time pop first one.

public int nthUglyNumber(int n) {
        SortedSet<Long> s1 = new TreeSet<>();
        s1.add((long)1);
        long result = s1.first();
        for(int i=0;i<n;i++){
            result = s1.first();
            s1.add(result * 2);
            s1.add(result * 3);
            s1.add(result * 5);
            s1.remove(result);
        }
        return (int)result;
    }


版权声明:本文为博主原创文章,未经博主允许不得转载。

[Leetcode 264] Ugly Number II

标签:leetcode   math   

原文地址:http://blog.csdn.net/sbitswc/article/details/48168159

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!