313:超级丑数

This commit is contained in:
huangge1199@hotmail.com 2021-08-09 23:15:54 +08:00
parent 4223806fbc
commit 3a0d70ee93
2 changed files with 121 additions and 0 deletions

View File

@ -0,0 +1,81 @@
//超级丑数 是一个正整数并满足其所有质因数都出现在质数数组 primes
//
// 给你一个整数 n 和一个整数数组 primes 返回第 n 超级丑数
//
// 题目数据保证第 n 超级丑数 32-bit 带符号整数范围内
//
//
//
// 示例 1
//
//
//输入n = 12, primes = [2,7,13,19]
//输出32
//解释给定长度为 4 的质数数组 primes = [2,7,13,19] 12 个超级丑数序列为[1,2,4,7,8,13,14,16,19,26,
//28,32]
//
// 示例 2
//
//
//输入n = 1, primes = [2,3,5]
//输出1
//解释1 不含质因数因此它的所有质因数都在质数数组 primes = [2,3,5]
//
//
//
//
//
//
// 提示
//
//
// 1 <= n <= 106
// 1 <= primes.length <= 100
// 2 <= primes[i] <= 1000
// 题目数据 保证 primes[i] 是一个质数
// primes 中的所有值都 互不相同 且按 递增顺序 排列
//
//
//
//
// Related Topics 数组 哈希表 数学 动态规划 优先队列
// 👍 249 👎 0
package leetcode.editor.cn;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Set;
//313:超级丑数
class SuperUglyNumber {
public static void main(String[] args) {
//测试代码
Solution solution = new SuperUglyNumber().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int nthSuperUglyNumber(int n, int[] primes) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add(1);
Set<Integer> seen = new HashSet<>();
for(int i=1;i<n;i++){
int cur = pq.poll();
for(int p: primes){
// 防止爆int处理
if(p > Integer.MAX_VALUE / cur)
break;
if(!seen.contains(cur * p)){
seen.add(cur * p);
pq.add(cur * p);
}
}
}
return pq.poll();
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,40 @@
<p><strong>超级丑数</strong> 是一个正整数,并满足其所有质因数都出现在质数数组 <code>primes</code> 中。</p>
<p>给你一个整数 <code>n</code> 和一个整数数组 <code>primes</code> ,返回第 <code>n</code><strong>超级丑数</strong></p>
<p>题目数据保证第 <code>n</code><strong>超级丑数</strong><strong>32-bit</strong> 带符号整数范围内。</p>
<p>&nbsp;</p>
<p><strong>示例 1</strong></p>
<pre>
<strong>输入:</strong>n = 12, <code>primes</code> = <code>[2,7,13,19]</code>
<strong>输出:</strong>32
<strong>解释:</strong>给定长度为 4 的质数数组 primes = [2,7,13,19],前 12 个超级丑数序列为:[1,2,4,7,8,13,14,16,19,26,28,32] 。</pre>
<p><strong>示例 2</strong></p>
<pre>
<strong>输入:</strong>n = 1, primes = [2,3,5]
<strong>输出:</strong>1
<strong>解释:</strong>1 不含质因数,因此它的所有质因数都在质数数组 primes = [2,3,5] 中。
</pre>
&nbsp;
<div class="top-view__1vxA">
<div class="original__bRMd">
<div>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 &lt;= n &lt;= 10<sup>6</sup></code></li>
<li><code>1 &lt;= primes.length &lt;= 100</code></li>
<li><code>2 &lt;= primes[i] &lt;= 1000</code></li>
<li>题目数据<strong> 保证</strong> <code>primes[i]</code> 是一个质数</li>
<li><code>primes</code> 中的所有值都 <strong>互不相同</strong> ,且按 <strong>递增顺序</strong> 排列</li>
</ul>
</div>
</div>
</div>
<div><div>Related Topics</div><div><li>数组</li><li>哈希表</li><li>数学</li><li>动态规划</li><li>堆(优先队列)</li></div></div>\n<div><li>👍 249</li><li>👎 0</li></div>