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;
}
}
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一秒钟。留个言点个赞呗,谢谢你#