LeetCode 264. 丑数 II
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 264. 丑数 II
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
264. 丑數 II
Ideas
竟然沒想到用小根堆,白學了,再把小根堆抄一遍。
Code
Python
class Solution:def nthUglyNumber(self, n: int) -> int:heap, seen = [1], {1}for i in range(n - 1):cur = heapq.heappop(heap)for factor in [2, 3, 5]:if (item := cur * factor) not in seen:seen.add(item)heapq.heappush(heap, item)return heapq.heappop(heap)C++
class Solution { public:int nthUglyNumber(int n) {vector<int> factors = {2, 3, 5};unordered_set<long> visit;priority_queue<long, vector<long>, greater<long>> heap;visit.insert(1L);heap.push(1L);int ugly = 0;for (int i = 0; i < n; i++) {long cur = heap.top();heap.pop();ugly = (int)cur;for (int factor: factors) {long next = cur * factor;if (!visit.count(next)) {visit.insert(next);heap.push(next);}}}return ugly;} }; 與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的LeetCode 264. 丑数 II的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 手把手教你Android Studio的
- 下一篇: LeetCode 208. 实现 Tri