Share My C Solution


  • 0
    R
    int nthUglyNumber(int n) {
    
        if (n == 1){
            return 1;
        }
        
        int currentUglyOrder = 1, currentUglyNum = 1;
        int uglyMultipler[3] = {0,0,0}
            ,uglyNo[3] = {2,3,5}
            ,uglyProduct[3] = {2,3,5}
            ,uglyList[10000] = {1};
        
        while(currentUglyOrder++ != n){
            /* update uglyProducts such that uglyProducts > currentUglyNum */
            for(int i=0; i < 3; ++i) {
                if (currentUglyNum >= uglyProduct[i]) {
                    /* uglyProducts = uglyNo (2,3,5) * previous ugly no */
                    uglyProduct[i] = uglyNo[i] * uglyList[++uglyMultipler[i]];
                }
            }
            
            /* currentUglyNum = min(uglyProduct(2), uglyProduct(3), uglyProduct(5)) */
            currentUglyNum = uglyProduct[0];
            for(int i=1; i < 3; ++i) {
                if (uglyProduct[i] < currentUglyNum) {
                    currentUglyNum = uglyProduct[i];
                }
            }
            
            /* update uglyNum List*/
            uglyList[currentUglyOrder-1] = currentUglyNum;
        }
        
        return currentUglyNum;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.