【LeetCode】Jianzhi Offer(25)

Table of contents

Title: Sword Pointing to Offer 49. Ugly Numbers - Leetcode

The interface of the topic:

Problem-solving ideas:

code:

It's over! ! !

Write at the end:


Title: Sword Pointing to Offer 49. Ugly Numbers - Leetcode

The interface of the topic:

class Solution {
public:
    int nthUglyNumber(int n) {

    }
};

Problem-solving ideas:

The question of ugly numbers uses a little bit of dynamic programming thinking,

The specific ideas are as follows:

According to the title:

If the first ugly number is one, the numbers containing prime factors 2, 3 and 5 are called ugly numbers,

Then we found that the following ugly numbers:

1, 2, 3, 4, 5, 6, 8, 9, 10, 12are the first 10 ugly numbers.

They are obtained by multiplying the previous ugly numbers by 2, 3 or 5.

Then our thinking can become:

Starting from the first number 1, let him multiply by 2, by 3, by 5,

Do the same for the second number,

Then take their minimum value as the next ugly number,

and so on, 

Three pointers are used to multiply by 2, multiply by 3, and multiply by 5 respectively.

The pointer with the minimum value points to the next number,

If two numbers are equal,

example:

2 * 5 == 5 * 2

Then both pointers point to the next number,

prevent duplication,

Finally, just return the nth ugly number.

example:

According to the rules: starting from the first number 1, let him multiply by 2, by 3, by 5

One by two, the pointer goes back one:

One by three, the pointer goes back one:

At this time, two times two is smaller than one times five,

So here goes two times two:

  

Then one by five:

 

 By analogy, the subsequent ugly numbers can be calculated.

 Here is the code:

code:

class Solution {
public:
    int nthUglyNumber(int n) {
        //创建n + 1大小的数组
        vector<int> dp(n + 1);

        //初始化三指针   
        int a = 0, b = 0, c = 0;

        //数组从1开始
        dp[0] = 1;

        //循环
        for(int i = 1; i < n; i++)
        {
            //让三指针*2 *3 *5 并选出最小值,就是下一个丑数
            int n2 = dp[a] * 2, n3 = dp[b] * 3, n5 = dp[c] * 5;

            //取最小值
            dp[i] = min(min(n2, n3), n5);

            //如果该下标对应的数是下一个丑数,就让指针指向下一个
            //如果有两个数结果相同,就让那两个指针都指向下一个
            //防止重复
            if(n2 == dp[i])
            {
                a++;
            }
            if(n3 == dp[i])
            {
                b++;
            }
            if(n5 == dp[i])
            {
                c++;
            }
        }
        //最后返回第n个丑数
        return dp[n - 1];
    }
};

It's over! ! !

Write at the end:

The above is the content of this article, thank you for reading.

If you like this article, please like and comment, and write down your opinions.

If you want to learn programming with me, you might as well follow me, we will learn and grow together.

I will output more high-quality content in the future, welcome to watch.

Guess you like

Origin blog.csdn.net/Locky136/article/details/129437995