dimanche 28 mars 2021

Solution of Finding nth Ugly Number

Hello I have a question of a solution of LC264- Ugly Number.

Given an integer index, return the index-th ugly number. Ugly number is a positive number whose prime factors only include 2, 3, and/or 5.

A possible solution is at below:


import java.lang.Math;
public class Solution {
    public int GetUglyNumber_Solution(int index) {
        
        if(index<1){
            return 0;
        }
        int i2=0;
        int i3=0;
        int i5=0;
        
        int[]dp=new int[index];
        dp[0]=1;
        for(int ugly=1;ugly<index;ugly++){
            int t2=dp[i2]*2;
            int t3=dp[i3]*3;
            int t5=dp[i5]*5;
            dp[ugly]=Math.min(t2,Math.min(t3,t5));
            if(t2==dp[ugly]){
                i2++;
            }
            if(t3==dp[ugly]){
                i3++;
            }
            if(t5==dp[ugly]){
                i5++;
            }
            
        }
        return dp[index-1];
    }
}

If I change the aforementioned algorithm to below, and remain other parts the same, the result is wrong.

            if(t2==dp[ugly]){
                i2++;
            }else if(t3==dp[ugly]){
                i3++;
            }else{
                i5++;
            }

So I do not understand why I can't use "if-else if-else", instead of using 3 if-judgements? Thanks!

Aucun commentaire:

Enregistrer un commentaire