leetcode oj java 264. Ugly Number II

来源:互联网 发布:中电云集 阿里云 编辑:程序博客网 时间:2024/05/08 13:31

一、问题描述:

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.


二、解决思路:

用数组依次保存ugly number .初始化 ug[0] = 1, ug[1] = 2

       在生成ug[k] 的时候 用M2 记录k之前所有元素乘2之后第一个超过ug[k-1] 的数, 用M3 记录k之前所有元素乘3之后第一个超过ug[k-1] 的数,用M5记录k之前所有元素乘5之后第一个超过ug[k-1] 的数. M2 M3 M5中的最小值即为ug[k].


三、代码:

package T01;/** * @author 作者 : xcy * @version 创建时间:2017年1月1日 下午10:02:34 *          类说明 */public class t263 {    public static void main(String[] args) {        // TODO Auto-generated method stub        int num = 9;        System.out.println(nthUglyNumber(num));    }    public static int nthUglyNumber(int n) {        int[] re = new int[n];        if (n == 1) {            return 1;        }        if (n == 2) {            return 2;        }        re[0] = 1;        re[1] = 2;        int M2 = 0, M3 = 0, M5 = 0;        int i2 = 0, i3 = 0, i5 = 0;        for (int i = 2; i < n; i++) {            // GEN m2            for (int j = i2; j < i; j++) {                if (2 * re[j] > re[i - 1]) {                    M2 = 2 * re[j];                    i2 = j;                    break;                }            }            // GEN m3            for (int j = i3; j < i; j++) {                if (3 * re[j] > re[i - 1]) {                    M3 = 3 * re[j];                    i3 = j;                    break;                }            }            // GEN m2            for (int j = i5; j < i; j++) {                if (5 * re[j] > re[i - 1]) {                    M5 = 5 * re[j];                    i5 = j;                    break;                }            }            int min = M2 < M3 ? M2 : M3;            min = min < M5 ? min : M5;            re[i] = min;        }        return re[n - 1];    }}
Tips:  


在生成M2 的时候,不需要从头开始,只需要从上一个生成M2的位置开始即可。因此用I2记录上一次生成M2的位置。M3,M5同理

0 0
原创粉丝点击