剑指Offer-数组-(9)

知识点/数据结构:数组

题目描述:
把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。

这是用友的笔试题:AC了!很开心!

代码如下

public class Solution {
    public int GetUglyNumber_Solution(int index) {
     
        if(index<=0)  {return 0;}
        int[] result = new int[index];
        int count = 0;
        
        int a = 0;
        int b = 0;
        int c = 0;
 
        result[0] = 1;
        int tmp = 0;
        
        while (count < index-1) {
            tmp = min(result[a] * 2, min(result[b] * 3, result[c] * 5));
            
            if(tmp==result[a] * 2) {a++;}//三条if防止值是一样的,不要改成else的
            if(tmp==result[b] * 3) {b++;}
            if(tmp==result[c]*5) {c++;}
            
            result[++count]=tmp;
        }
        return result[index - 1];
    }
 
    private int min(int a, int b) {
        return (a > b) ? b : a;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_35649064/article/details/84853325