首页 > 其他 > 详细

[Leetcode 264] Ugly Number II

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

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!