386. 字典序排数
给你一个整数 n ,按字典序返回范围 [1, n] 内所有整数。
你必须设计一个时间复杂度为 O(n) 且使用 O(1) 额外空间的算法。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lexicographical-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
class Solution {
public List<Integer> lexicalOrder(int n) {
List<Integer> ans = new ArrayList<>();
long prefix = 1;
while (ans.size() < n) {
ans.add((int) prefix);
if (prefix * 10 <= n) {
prefix *= 10;
} else {
while (prefix % 10 == 9 || prefix + 1 > n) {
prefix /= 10;
}
prefix++;
}
}
return ans;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
new Solution().lexicalOrder(in.nextInt()).forEach(System.out::println);
}
}
}
心之所向,素履以往 生如逆旅,一苇以航

浙公网安备 33010602011771号