Did anyone use an array approach?


  • 0

    Got TLE. But it might be a different approach.

    public class Solution {
        public int findNthDigit(int n) {
            if (n <= 9) {
                return n;
            }
            int[] digits = new int[32];
            for (int i = 0; i < digits.length; i += 1) {
                digits[i] = -1;
            }
            digits[0] = 9;
            int i = 9, index = 0;
            while (i < n) {
                i += 1;
                index += 1;
                if (digits[index] == -1) {
                    digits[index - 1] += 1;
                    int prev = index - 1;
                    while (prev > 0 && digits[prev] == 10) {
                        digits[prev] = 0;
                        prev -= 1;
                        digits[prev] += 1;
                    }
                    if (digits[0] == 10) {
                        digits[0] = 1;
                        digits[index] = 0;
                    }
                    index = 0;
                }
            }
            return digits[index];
        }
    }
    

Log in to reply
 

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