丑数II

2017-02-28  本文已影响0人  Yui丶西米大人

题目描述

设计一个算法,找出只含素因子2,3,5 的第 n 大的数。1也是一个丑数。

思路

代码

 int nthUglyNumber(int n) {
        // Write your code here
        int index2 = 0;
        int index3 = 0;
        int index5 = 0;
        int[] res = new int[n];
        res[0] = 1;
        int count = 1;
        while(count < n){
            res[count] = min(res[index2]*2, res[index3]*3, res[index5]*5);
            if(res[count] == res[index2]*2) index2++;
            if(res[count] == res[index3]*3) index3++;
            if(res[count] == res[index5]*5) index5++;
            count++;
        }
        return res[--count];
    }
    private int min(int a1, int a2, int a3){
        if(a1 < a2){
            if(a1 < a3)
                return a1;
            else
                return a3;
        }else if(a2 < a3){
            return a2;
        }else{
            return a3;
        }
    }

考差点

上一篇 下一篇

猜你喜欢

热点阅读