Leetcode--264. 丑数Ⅱ

编写一个程序,找出第 n 个丑数。

丑数就是只包含质因数 2, 3, 5 的正整数。

示例:

输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。
说明:  

1 是丑数。
n 不超过1690。

思路:从1开始,需要对每个值都乘以2,3,5,然后判断大小把他们依次放入数组

设置三个指针位,各自独立地向后遍历,实现这个目标

提交的代码:

class Solution {
    public int nthUglyNumber(int n) {
        int x,y,z,i,j=1;
        int[] nums = new int[1690];
        nums[0] = 1;
        x = 0;
        y = 0;
        z = 0;
        for(i=1;i<n;i++)
        {
            j = java.lang.Math.min(nums[x]*2, java.lang.Math.min(nums[y]*3,nums[z]*5));
            if(nums[x]*2==j)
            {
                nums[i]=j;
                x++;
            }
            if(nums[y]*3==j)    //不可用else if,否则如果x位于第三个位置3处,y位于第二个位置2处,会出现重复的数字(2*3=3*2)
            {
                nums[i]=j;
                y++;
            }
            if(nums[z]*5==j)
            {
                nums[i]=j;
                z++;
            }       
        }
        return nums[n-1];
    }
}

完整的代码:
import java.util.Scanner;

public class Soluiton264 {
    public static int nthUglyNumber(int n) {
        int x,y,z,i,j=1;
        int[] nums = new int[1690];
        nums[0] = 1;
        x = 0;
        y = 0;
        z = 0;
        for(i=1;i<n;i++)
        {
            j = java.lang.Math.min(nums[x]*2, java.lang.Math.min(nums[y]*3,nums[z]*5));
            if(nums[x]*2==j)
            {
                nums[i]=j;
                x++;
            }
            if(nums[y]*3==j)
            {
                nums[i]=j;
                y++;
            }
            if(nums[z]*5==j)
            {
                nums[i]=j;
                z++;
            }       
        }
        return nums[n-1];
    }
    public static void main(String[] args)
    {
        Scanner scanner = new Scanner(System.in);
        int x = scanner.nextInt();
        System.out.println(nthUglyNumber(x));

    }
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值