?LeetCode刷題實(shí)戰(zhàn)386:字典序排數(shù)
Given an integer n, return all the numbers in the range [1, n] sorted in lexicographical order.
You must write an algorithm that runs in O(n) time and uses O(1) extra space.
示例
給定 n =1 3,返回 [1,10,11,12,13,2,3,4,5,6,7,8,9] 。
請(qǐng)盡可能的優(yōu)化算法的時(shí)間復(fù)雜度和空間復(fù)雜度。輸入的數(shù)據(jù) n 小于等于 5,000,000。
解題
class Solution {
public:
vector<int> lexicalOrder(int n) {
vector<int> nums(n,0);
for(int i=0;i<n;++i){//存入范圍內(nèi)的所有數(shù)字
nums[i]=i+1;
}
//使用自定義函數(shù)進(jìn)行排序
sort(nums.begin(),nums.end(),[](int& lhs,int& rhs){
//先將兩個(gè)整數(shù)轉(zhuǎn)成字符串,使用字符串進(jìn)行比較
string str1=to_string(lhs);
string str2=to_string(rhs);
int pos=0;
while(pos<str1.size()||pos<str2.size()){
if(pos<str1.size()&&pos<str2.size()){//都在范圍內(nèi),比較字符的大小
if(str1[pos]<str2[pos]){
return true;
}
else if(str1[pos]>str2[pos]){//不在范圍內(nèi),比較字符串的長(zhǎng)度
return false;
}
}
else if(str1.size()<str2.size()){
return true;
}
else{
return false;
}
++pos;
}
return true;
});
return nums;
}
};
LeetCode1-380題匯總,希望對(duì)你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)381:O(1) 時(shí)間插入、刪除和獲取隨機(jī)元素
LeetCode刷題實(shí)戰(zhàn)382:鏈表隨機(jī)節(jié)點(diǎn)
LeetCode刷題實(shí)戰(zhàn)383:贖金信
LeetCode刷題實(shí)戰(zhàn)384:打亂數(shù)組
LeetCode刷題實(shí)戰(zhàn)385:迷你語(yǔ)法分析器
