| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.UglyNumber2; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class UglyNumber2PriorityQueue : IUglyNumber2 |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n log n) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="n"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public int NthUglyNumber(int n) |
| 9 | 24 | | { |
| 9 | 25 | | var hashSet = new HashSet<long>(); |
| 9 | 26 | | var priorityQueue = new PriorityQueue<long, long>(); |
| 9 | 27 | | priorityQueue.Enqueue(1, 1); |
| | 28 | |
|
| 9 | 29 | | long current = 1; |
| | 30 | |
|
| 13160 | 31 | | while (hashSet.Count < n) |
| 13151 | 32 | | { |
| 13151 | 33 | | current = priorityQueue.Dequeue(); |
| | 34 | |
|
| 13151 | 35 | | if (!hashSet.Add(current)) |
| 7970 | 36 | | { |
| 7970 | 37 | | continue; |
| | 38 | | } |
| | 39 | |
|
| 5181 | 40 | | priorityQueue.Enqueue(current * 2, current * 2); |
| 5181 | 41 | | priorityQueue.Enqueue(current * 3, current * 3); |
| 5181 | 42 | | priorityQueue.Enqueue(current * 5, current * 5); |
| 5181 | 43 | | } |
| | 44 | |
|
| 9 | 45 | | return (int)current; |
| 9 | 46 | | } |
| | 47 | | } |