Lexicographical Numbers

来源:互联网 发布:java iterator hashmap 编辑:程序博客网 时间:2024/05/22 17:26

 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.

Subscribe to see which companies asked this question.

解析:挺巧妙的题,刚开始使用排序的方法超时。其实按字母排序每次*10是接下来的数,如果超过n,且最后一位不是9,则加1,若果后面几位是9则除以10直到末尾不是9再加1。

代码:

class Solution {public:    vector<int> lexicalOrder(int n) {       vector<int>ans;              int cur=1;       for (int i=1; i<=n; i++)       {           ans.push_back(cur);           if (cur*10<=n)           {               cur*=10;           }           else if (((cur+1)<=n)&&(cur%10!=9))           {               cur++;           }           else           {               while(cur%10==9||cur==n)               {                   cur/=10;               }               cur++;           }       }       return ans;    }};



0 0