Re: [閒聊] 每日leetcode
看板Marginalman作者enmeitiryous (enmeitiryous)時間1年前 (2024/09/21 08:57)推噓1(1推 0噓 2→)留言3則, 2人參與討論串887/1548 (看更多)
題目:386. Lexicographical Numbers
給你一個數字n求以lexicographical order排序的1-n的數字順序
思路:
lexicographical order就是字串排序的方式例如2>17>10這樣,所以也可以暴力的把1到n
的數字全部轉字串後排序,比較好也滿足題目要求作法是:從1開始塞,如果*10比n小
下一個就塞上一個塞的數*10,不然的話假如這個要塞的數尾數是9(+1會改變上一位數,
下一個要塞的數會違反字典序例如109下一個是11而不是110)或是為n(代表可以回去塞比
n小一位數但字典序>n的數)則/=10,直到滿足條件後再+1
vector<int> lexicalOrder(int n) {
vector<int> pre_ans;
int a=1;
for(int i=0;i<n;++i){
pre_ans.push_back(a);
if(10*a<=n){
a*=10;
}
else{
while(a%10==9 || a==n){
a/=10;
}
a+=1;
}
}
return pre_ans;
}
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.227.196.198 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1726880256.A.2DC.html
→
09/21 09:08,
1年前
, 1F
09/21 09:08, 1F
→
09/21 09:08,
1年前
, 2F
09/21 09:08, 2F
推
09/21 12:08,
1年前
, 3F
09/21 12:08, 3F
討論串 (同標題文章)
完整討論串 (本文為第 887 之 1548 篇):