[LC 264] Ugly number II

First thought: iterate from 1 to n, check if the current number is ugly. When a number has a factor that has been identified as ugly, no need to check further. But this algorithm got TLE. Because most numbers are not ugly.
Second thought:  generate ugly number only. Check http://www.geeksforgeeks.org/ugly-numbers/
    public int nthUglyNumber(int n) {
        int[] ugly = new int[n];
        ugly[0] = 1;
        int i2 = 0;
        int i3 = 0;
        int i5 = 0;
        for (int i = 1; i < n; i++) {
            int m2 = ugly[i2] * 2;
            int m3 = ugly[i3] * 3;
            int m5 = ugly[i5] * 5;
            // one possible bug here: if more than one multiplier (m2, m3, m5) equals “min”, need to increase all indices (i2, i3, or i5)
            int min = Math.min(m2, Math.min(m3, m5));
            ugly[i] = min;
            if (m2 == min) {
                i2++;
            }
            if (m3 == min) {
                i3++;
            }
            if (m5 == min) {
                i5++;
            }
        }
        return ugly[n-1];
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s