264. Ugly Number II

来源:互联网 发布:java系统日志记录 编辑:程序博客网 时间:2024/06/07 20:33

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, 12is the sequence of the first 10 ugly numbers.

Note that 1 is typically treated as an ugly number, and n does not exceed 1690.

java

class Solution {    public int nthUglyNumber(int n) {        if (n <= 0) {            return -1;        }        if (n == 1) {            return 1;        }        Queue<Long> queue = new PriorityQueue<>();        Set<Long> set = new HashSet<>();        int[] arr = new int[3];        queue.offer(Long.valueOf(1));        set.add(Long.valueOf(1));        arr[0] = 2;        arr[1] = 3;        arr[2] = 5;        Long val;        for (int i = 0; i < n; i++) {            val = queue.poll();            for (int j = 0; j < 3; j++) {                if (!set.contains(arr[j] * val)) {                    queue.offer(arr[j] * val);                    set.add(arr[j] * val);                }            }        }        return val;    }}