Problem description
Ugly number is a number, which only has factors 3, 5, and 7.
Design an algorithm to find the Kth ugly number. The first 5 ugly numbers is 3, 5, 7, 9, 15 ...
Problem analysis
This problem, there are many ways to solve, the common is that there are auxiliary data structures, such as priority_queue, or often said the largest minimum heap can also.
Solution One: Time complexity O (k log k), Space complexity O (k)
- Use Priority_queue to simulate the smallest heap:
priority_queue<int, vector<int>, greater<int> >
. Remove the smallest ugly number from it, then multiply the ugly number by 3, 5, 7, and then into priority_queue
the
- If the above procedure, multiply the number of 3,5,7 after the direct put into
priority_queue
the problem that may result in repeated putting, for example: When Remove 9, and then put 27, 45, 63,. After taking out the 21 o'clock, put 63, 105, 147, here to repeat put 63. So you need to use a unordered_set<int>
mark which elements have been put in.
Time complexity Analysis: a total of k elements, each time you take out an element, you need to operate the heap, the time complexity of O (k), so the time complexity of O (k log k).
Solution Two: Time complexity O (k), Spatial complexity O (k)
- Use a primes array to record the first k ugly_number. When generating an primes array, the added element is definitely the number of elements in the primes array multiplied by 3, or multiplied by 5, or multiplied by the 7 result, and is the smallest. Based on this idea, the following code can be constructed
classSolution { Public:/ * * @param k:the number k. * @return: The kth prime number as description. */ Long LongKthprimenumber (intK) {//Write your code here vector<long long>Primes (k +1); primes[0] =1;inti3 =0, i5 =0, i7 =0; for(inti =1; I <= K; i++) {Long Longnextprime = min (min (primes[i3]*3, primes[i5]*5), primes[i7]*7);if(NextPrime = = primes[i3]*3) i3++;if(NextPrime = = primes[i5]*5) i5++;if(NextPrime = = primes[i7]*7) i7++; Primes[i] = NextPrime; }returnPRIMES[K]; }};
Complexity analysis: Now only the K operation is required, each operation time is O (1), so the total time complexity is O (k), and the total time complexity is O (k).
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
lintcode:ugly number