LeetCode(263 & 264):丑数 I II Ugly Number I II(Java)

234 篇文章 1 订阅
177 篇文章 0 订阅

2020.12.30 LeetCode 从零单刷个人笔记整理(持续更新)

github:https://github.com/ChopinXBP/LeetCode-Babel

丑数I只需要验证是否为丑数即可,直接将其除净即可。丑数II要求返回指定顺位的丑数,可以采用归并的思想。

用三指针指向下一个需要乘n(n=2/3/5)进行拓展的数字,相当于做一个三路归并。

找出三个指针的最小元素,将指针后移。如果有多组指针的当前值都是min,指针都需要后移,保证 ugly 数组中不会加入重复元素。


传送门:丑数

Write a program to check whether a given number is an ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.

编写一个程序判断给定的数是否为丑数。

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

示例 1:
输入: 6
输出: true
解释: 6 = 2 × 3

示例 2:
输入: 8
输出: true
解释: 8 = 2 × 2 × 2

示例 3:
输入: 14
输出: false 
解释: 14 不是丑数,因为它包含了另外一个质因数 7。

说明:
1 是丑数。
输入不会超过 32 位有符号整数的范围: [−231,  231 − 1]。


package Problems;

/**
 *
 * Write a program to check whether a given number is an ugly number.
 * Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
 * 编写一个程序判断给定的数是否为丑数。
 * 丑数就是只包含质因数 2, 3, 5 的正整数。
 *
 */

public class UglyNumber {
    public boolean isUgly(int num) {
        if (num < 1){
            return false;
        }
        while (num % 5 == 0){
            num /= 5;
        }
        while (num % 3 == 0){
            num /= 3;
        }
        while ((num & 1) == 0){
            num >>= 1;
        }
        return num == 1;
    }
}




传送门:丑数 II

Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.

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

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

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

说明:  
1 是丑数。
n 不超过1690。


package Problems;

/**
 *
 * Write a program to find the n-th ugly number.
 * Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
 * 编写一个程序,找出第 n 个丑数。
 * 丑数就是只包含质因数 2, 3, 5 的正整数。
 *
 */

public class UglyNumberII {
    public int nthUglyNumber(int n) {
        int[] ugly = new int[n];
        ugly[0] = 1;
        int index2 = 0, index3 = 0, index5 = 0;
        for (int i = 1; i < n; i++) {
            //相当于三路归并
            int factor2 = 2 * ugly[index2];
            int factor3 = 3 * ugly[index3];
            int factor5 = 5 * ugly[index5];
            int min = Math.min(Math.min(factor2, factor3), factor5);
            ugly[i] = min;
            //找出三个指针的最小元素,将指针后移
            //如果有多组指针的当前值都是 min,指针都需要后移,保证 ugly 数组中不会加入重复元素。
            if (factor2 == min)
                index2++;
            if (factor3 == min)
                index3++;
            if (factor5 == min)
                index5++;
        }
        return ugly[n - 1];
    }
}




#Coding一小时,Copying一秒钟。留个言点个赞呗,谢谢你#

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值