力扣专题——264.丑数 II

264.丑数 II

给你一个整数 n ,请你找出并返回第 n 个 丑数 。

丑数 就是只包含质因数 2、3 和/或 5 的正整数。

示例 1:

输入:n = 10
输出:12
解释:[1, 2, 3, 4, 5, 6, 8, 9, 10, 12] 是由前 10 个丑数组成的序列。

思路:
通过三指针写法来解决该问题。
三个指针分别表示该位置乘以2,3,5
使用min方法取其中最小的值添加到结果数组中
然后将值相同的指针加一,这样可以避免数据重复
整个流程也保证了最新添加的数的因数是2,3,5

源码:
python和c

class Solution:
    def nthUglyNumber(self, n: int) -> int:
        res=[1]
        index1=0
        index2=0
        index3=0
        for i in range(n-1):
            res.append(min(res[index1]*2,res[index2]*3,res[index3]*5))
            if(res[-1]==res[index1]*2):
                index1+=1
            if(res[-1]==res[index2]*3):
                index2+=1    
            if(res[-1]==res[index3]*5):
                index3+=1
        return res[-1]    

作者:shang-91
链接:https://leetcode-cn.com/problems/ugly-number-ii/solution/san-zhi-zhen-xie-fa-by-shang-91-0cpy/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
int nthUglyNumber(int n){
    int res[n+1];
    res[0]=1;
    int idx1=0,idx2=0,idx3=0;
    for(int i=1;i<n;i++){
        int no1=res[idx1]*2,no2=res[idx2]*3,no3=res[idx3]*5;
        res[i]=fmin(fmin(no1,no2),no3);
        if(res[i]==res[idx1]*2)
            idx1++;
        if(res[i]==res[idx2]*3)
            idx2++;
        if(res[i]==res[idx3]*5)
            idx3++;    
    }
    return res[n-1];
}

你可能感兴趣的:(leetcode,leetcode,算法,动态规划,python)