LeetCode 题解(188): 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. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note that 1 is typically treated as an ugly number.

题解:

查表:

1 * 2, 2* 2, 3* 2, .....

1* 3, 2* 3, 3*3,......

1* 5, 2 * 5, 3 * 5, .......

首先ugly number的序列由ugly number * 2, *3, *5得到,即以上三个序列,下一个ugly number为上面三个序列中当前最小的元素。出现重复元素时需要移动多个指针。

C++版:

class Solution {
public:
    int nthUglyNumber(int n) {
        vector<int> ugly(n, 1);
        int i2 = 0, i3 = 0, i5 = 0;
        for(int i = 1; i < n; i++) {
            int current = min(ugly[i2] * 2, min(ugly[i3] * 3, ugly[i5] * 5));
            ugly[i] = current;
            if(current == ugly[i2] * 2)
                i2++;
            if(current == ugly[i3] * 3)
                i3++;
            if(current == ugly[i5] * 5)
                i5++;
        }
        return ugly[n-1];
    }
};

Java版:

public class Solution {
    public int nthUglyNumber(int n) {
        int[] ugly = new int[n];
        ugly[0] = 1;
        int i2 = 0, i3 = 0, i5 = 0;
        for(int i = 1; i < n; i++) {
            int current = Math.min(ugly[i2] * 2, Math.min(ugly[i3] * 3, ugly[i5] * 5));
            ugly[i] = current;
            if(current == ugly[i2] * 2)
                i2++;
            if(current == ugly[i3] * 3)
                i3++;
            if(current == ugly[i5] * 5)
                i5++;
        }
        return ugly[n-1];
    }
}

Python版:

class Solution(object):
    def nthUglyNumber(self, n):
        """
        :type n: int
        :rtype: int
        """
        ugly = [1] * n
        i2, i3, i5 = 0, 0, 0
        for i in range(1, n):
            current = min(ugly[i2] * 2, min(ugly[i3] * 3, ugly[i5] * 5))
            ugly[i] = current
            if current == ugly[i2] * 2:
                i2 += 1
            if current == ugly[i3] * 3:
                i3 += 1
            if current == ugly[i5] * 5:
                i5 += 1
        return ugly[n-1]


你可能感兴趣的:(Algorithm,LeetCode,面试题)