July LeetCoding Challenge - 4

이선태·2020년 7월 5일
0

Leetcode challenge

목록 보기
4/8

Day4

Ugly Number II

문제

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:

  1. is typically treated as an ugly number.
    n does not exceed 1690.

Hint

  1. The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones.
  2. An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.
  3. The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3.
  4. Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 2, L2 3, L3 * 5).

답(Java)

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만 곱하는 리스트 모두 다음 수로 넘어가도록 처리했다.

profile
퀀트 트레이딩, 통계에 관심이 많아요

0개의 댓글