Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
Example:
Input: n = 10
Output: 12
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
Note:
Hint
class Solution {
public int nthUglyNumber(int n) {
int[] list = new int[n];
list[0] = 1;
int l1 = 0, l2 = 0, l3 = 0;
for (int i = 1; i < n; i++) {
int m2 = list[l1] * 2;
int m3 = list[l2] * 3;
int m5 = list[l3] * 5;
list[i] = Math.min(Math.min(m2, m3), m5);
if (list[i] == m2)
l1++;
if (list[i] == m3)
l2++;
if (list[i] == m5)
l3++;
}
return list[n-1];
}
}
힌트없이 알고리즘을 떠올리기 어려웠던 문제다. 2, 3, 5만 인수로 갖는 수를 차례대로 생성해야 하므로 1부터 시작하여 2, 3, 5를 순서대로 곱해주는 방법은 생각했지만 대소 비교랑, 중복 처리를 어떻게 해야할지 고민이었다. 이때 4번 힌트가 많은 도움이 되었다. 2만 곱하는 리스트, 3만 곱하는 리스트, 5만 곱하는 리스트를 구별하여 가장 작은 값을 다음 Ugly number로 추가하는 방식으로 구현했다. 2x3과 3x2 처럼 같은 수를 계산하는 경우에는 2만 곱하는 리스트와 3만 곱하는 리스트 모두 다음 수로 넘어가도록 처리했다.