[Leetcode] 丑数问题
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
. For example, 6, 8
are ugly while 14
is not ugly since it includes another prime factor 7
.
Note that 1
is typically treated as an ugly number.
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.
又是一个找第K小的问题,老题重谈了。
一般思路都是从当前最小,找出后面的数字,并且放到优先队列当中去进行保存。
一、ugly number
1 public class Solution { 2 public boolean isUgly(int num) { 3 if(num<=0) return false; 4 if(num==1) return true; 5 while(num!=1){ 6 if(num%2==0) num/=2; 7 else if(num%3==0) num/=3; 8 else if(num%5==0) num/=5; 9 else return false; 10 } 11 return true; 12 } 13 }
二、ugly number II
1 import java.util.*; 2 3 public class Solution { 4 public int nthUglyNumber(int n) { 5 if(n==1) return 1; 6 //这里需要使用Double来保存数据,使用int会溢出 7 PriorityQueue<Double> q2 = new PriorityQueue<Double>(); 8 PriorityQueue<Double> q3 = new PriorityQueue<Double>(); 9 PriorityQueue<Double> q5 = new PriorityQueue<Double>(); 10 q2.offer(1.0); 11 double min =1; 12 for(int i=1;i<=n;i++){ 13 min = q2.peek().intValue(); 14 min = !q3.isEmpty()&&q3.peek().intValue()<min? q3.peek().intValue():min; 15 min = !q5.isEmpty()&&q5.peek().intValue()<min? q5.peek().intValue():min; 16 if(min==q2.peek().intValue()){ 17 q2.poll(); 18 q2.offer(2*min); 19 q3.offer(3*min); 20 q5.offer(5*min); 21 }else if(min==q3.peek().intValue()){ 22 q3.poll(); 23 q3.offer(3*min); 24 q5.offer(5*min); 25 }else{ 26 q5.poll(); 27 q5.offer(min*5); 28 } 29 } 30 return (int)min; 31 } 32 }