Sword Finger Offer—49. Ugly Numbers—Analysis and Code (Java)

1. Title

The numbers that only contain prime factors 2, 3, and 5 are called Ugly Numbers. For example, 6 and 8 are both ugly numbers, but 14 is not because it contains the prime factor 7. Traditionally, we regard 1 as the first ugly number. Find the Nth ugly number in ascending order.

Two, analysis and code

1. Mark the position + solve in turn

(1) Thinking

Since the ugly numbers only contain prime factors 2, 3 and 5, the ugly numbers can be obtained by multiplying these three factors together in ascending order.
In the calculation process, the next ugly number comes from a generated ugly number multiplied by 2, 3 or 5, and the generated ugly number array is ordered. You can design 3 marks to record the most recent time and each factor respectively Multiply the position of the data used to generate the required ugly number, thereby avoiding repeated operations.

(2) Code

import java.util.*;
public class Solution {
    
    
    public int GetUglyNumber_Solution(int index) {
    
    
        if (index <= 0)
            return 0;
        ArrayList<Integer> uglyNums = new ArrayList<>();
        uglyNums.add(1);
        
        int i2 = 0, i3 = 0, i5 = 0;
        int num2 = uglyNums.get(i2++) * 2;
        int num3 = uglyNums.get(i3++) * 3;
        int num5 = uglyNums.get(i5++) * 5;
        
        for (int i = 1; i < index; i++) {
    
    
            int num = Math.min(num2, Math.min(num3, num5));
            uglyNums.add(num);
            if (num == num2)
                num2 = uglyNums.get(i2++) * 2;
            if (num == num3)
                num3 = uglyNums.get(i3++) * 3;
            if (num == num5)
                num5 = uglyNums.get(i5++) * 5;
        }
        return uglyNums.get(index - 1);
    }
}

(3) Results

Running time: 21ms, occupied memory: 9532k.

Three, other

Nothing.

Guess you like

Origin blog.csdn.net/zml66666/article/details/108987521