Skip to content

Commit 06b5b11

Browse files
committed
add solution of problem 386: lexicographical numbers
1 parent 8ddf876 commit 06b5b11

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Given an integer *n*, return 1 - *n* in lexicographical order.
2+
3+
For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
4+
5+
Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000.
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
public class Solution {
2+
public List<Integer> lexicalOrder(int n) {
3+
List<Integer> result = new ArrayList<Integer>();
4+
if (n <= 0)
5+
return result;
6+
7+
Stack<Integer> stack = new Stack();
8+
stack.push(1);
9+
10+
while (!stack.empty()) {
11+
int value = stack.pop();
12+
13+
while (value <= n) {
14+
if (value%10 <= 8 && value+1 <= n)
15+
stack.push(value + 1);
16+
17+
result.add(value);
18+
value *= 10;
19+
}
20+
}
21+
22+
return result;
23+
}
24+
}

0 commit comments

Comments
 (0)