386 Lexicographical Numbers

Given an integern, return 1 -nin lexicographical order.

For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9].

Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000.

19

499

res.add(curt)

if (curt * 10 <= n) curt = curt * 10;

else if (curt % 10 != 9 && curt .+ 1 <= n ) curt++

else

    while\( \(curt / 10 \) % 10 == 9\)

           curt = curt / 10;

   curt = curt/10 + 1;
class Solution {
    public List<Integer> lexicalOrder(int n) {
        List<Integer> ans = new ArrayList<>();
        if (n <= 0) {
            return ans;
        }
        int curt = 1;
        for (int i = 1; i <= n; i++) {
            ans.add(curt);
            if (curt * 10 <= n) {
                curt = curt * 10;
            }else if (curt % 10 != 9 && curt + 1 <= n) {
                curt++;
            }else {
                while ( (curt / 10) % 10 == 9) {
                    curt = curt / 10;
                }
                curt = curt / 10 + 1;
            }
        }
        return ans;
    }
}

results matching ""

    No results matching ""