comments | difficulty | edit_url | tags | ||
---|---|---|---|---|---|
true |
中等 |
|
给你一个整数 n
,按字典序返回范围 [1, n]
内所有整数。
你必须设计一个时间复杂度为 O(n)
且使用 O(1)
额外空间的算法。
示例 1:
输入:n = 13 输出:[1,10,11,12,13,2,3,4,5,6,7,8,9]
示例 2:
输入:n = 2 输出:[1,2]
提示:
1 <= n <= 5 * 104
我们首先定义一个变量
时间复杂度
class Solution:
def lexicalOrder(self, n: int) -> List[int]:
ans = []
v = 1
for _ in range(n):
ans.append(v)
if v * 10 <= n:
v *= 10
else:
while v % 10 == 9 or v + 1 > n:
v //= 10
v += 1
return ans
class Solution {
public List<Integer> lexicalOrder(int n) {
List<Integer> ans = new ArrayList<>(n);
int v = 1;
for (int i = 0; i < n; ++i) {
ans.add(v);
if (v * 10 <= n) {
v *= 10;
} else {
while (v % 10 == 9 || v + 1 > n) {
v /= 10;
}
++v;
}
}
return ans;
}
}
class Solution {
public:
vector<int> lexicalOrder(int n) {
vector<int> ans;
int v = 1;
for (int i = 0; i < n; ++i) {
ans.push_back(v);
if (v * 10 <= n) {
v *= 10;
} else {
while (v % 10 == 9 || v + 1 > n) {
v /= 10;
}
++v;
}
}
return ans;
}
};
func lexicalOrder(n int) (ans []int) {
v := 1
for i := 0; i < n; i++ {
ans = append(ans, v)
if v*10 <= n {
v *= 10
} else {
for v%10 == 9 || v+1 > n {
v /= 10
}
v++
}
}
return
}
function lexicalOrder(n: number): number[] {
const ans: number[] = [];
let v = 1;
for (let i = 0; i < n; ++i) {
ans.push(v);
if (v * 10 <= n) {
v *= 10;
} else {
while (v % 10 === 9 || v === n) {
v = Math.floor(v / 10);
}
++v;
}
}
return ans;
}
impl Solution {
pub fn lexical_order(n: i32) -> Vec<i32> {
let mut ans = Vec::with_capacity(n as usize);
let mut v = 1;
for _ in 0..n {
ans.push(v);
if v * 10 <= n {
v *= 10;
} else {
while v % 10 == 9 || v + 1 > n {
v /= 10;
}
v += 1;
}
}
ans
}
}
/**
* @param {number} n
* @return {number[]}
*/
var lexicalOrder = function (n) {
const ans = [];
let v = 1;
for (let i = 0; i < n; ++i) {
ans.push(v);
if (v * 10 <= n) {
v *= 10;
} else {
while (v % 10 === 9 || v === n) {
v = Math.floor(v / 10);
}
++v;
}
}
return ans;
};