【leetcode】264. Ugly Number II

    xiaoxiao2021-03-25  136

    一、题目描述

    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, and n does not exceed 1690.

    Hint:

    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.An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.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.Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).

    思路:剑指offer上的原题,不去考虑非丑数,后面的丑数都是由前面的丑数乘以2或者乘以3或者乘以5得到的,因此维护三个指针。

    c++代码(9ms,30.10%)

    class Solution { public: //返回a,b,c中最小的数 int Min(int a, int b, int c){ int tmp=a<b?a:b; return tmp<c?tmp:c; } int nthUglyNumber(int n){ //返回第n个丑数 int *uglyNumber = new int[n+1]; uglyNumber[0] = 1; int next_index=1; int *multiply_2 = uglyNumber; int *multiply_3 = uglyNumber; int *multiply_5 = uglyNumber; while(next_index<n){ int tmp=Min(*multiply_2*2, *multiply_3*3, *multiply_5*5); uglyNumber[next_index++] = tmp; while(((*multiply_2)*2) <= tmp){ multiply_2++; } while(((*multiply_3)*3) <= tmp){ multiply_3++; } while(((*multiply_5)*5) <= tmp){ multiply_5++; } } int res=uglyNumber[n-1]; delete[] uglyNumber; return res; } };

    转载请注明原文地址: https://ju.6miu.com/read-6699.html

    最新回复(0)