Leetcode 179. 最大数 解题思路及C++实现
生活随笔
收集整理的這篇文章主要介紹了
Leetcode 179. 最大数 解题思路及C++实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
解題思路:
使用C++中的優先隊列priority_queue,通過自定義比較函數cmp,來對nums數組進行排序。最后按排序結果,順序將nums中的數push_back進字符串res中,即得到結果。
?
class Solution { public:string largestNumber(vector<int>& nums) {if(nums.empty()) return "0";priority_queue<int, vector<int>, cmp> pq;for(auto num: nums){pq.push(num);}string res;while(pq.top() == 0 && !pq.empty()) pq.pop();while(!pq.empty()){res += to_string(pq.top());pq.pop();}if(res.empty()) return "0"; //nums數組中元素都為0的情況return res;}struct cmp{bool operator()(int a, int b){string tmpa = to_string(a);string tmpb = to_string(b);//不能使用stoi, int會超出限制if(stol(tmpa+tmpb) > stol(tmpb+tmpa)) return false;else return true;}}; };?
?
?
總結
以上是生活随笔為你收集整理的Leetcode 179. 最大数 解题思路及C++实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leetcode 148. 排序链表 解
- 下一篇: Leetcode 220. 存在重复元素