2018年7月4日 星期三

[LeetCode] week 1. Lexicographical Numbers

Lexicographical Numbers
https://leetcode.com/contest/warm-up-contest/problems/lexicographical-numbers/


Given an integer n, return 1 - n in 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.

class Solution:
    def lexicalOrder(self, n):
        
        """
        :type n: int
        :rtype: List[int]
        """
        
        curr = 1
        list1 = []
        count = 1
        while(count <= n):
            list1.append(curr)
            if(curr * 10 <= n):
                curr *= 10
            elif(curr % 10 != 9 and curr +1 <= n):
                curr+=1
            else:
                while(int(curr/10)%10==9):
                    curr/=10
                curr = int(curr/10 + 1)
            count += 1
        return list1

沒有留言:

張貼留言