C++實現(xiàn)LeetCode(179.最大組合數(shù))
[LeetCode] 179. Largest Number 最大組合數(shù)
Given a list of non negative integers, arrange them such that they form the largest number.
Example 1:
Input: [10,2]
Output: "210"
Example 2:
Input: [3,30,34,5,9]
Output: "9534330"
Note: The result may be very large, so you need to return a string instead of an integer.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
這道題給了我們一個數(shù)組,讓將其拼接成最大的數(shù),那么根據(jù)題目中給的例子來看,主要就是要給數(shù)組進行排序,但是排序方法不是普通的升序或者降序,因為9要排在最前面,而9既不是數(shù)組中最大的也不是最小的,所以要自定義排序方法。如果不參考網(wǎng)友的解法,博主估計是無法想出來的。這種解法對于兩個數(shù)字a和b來說,如果將其都轉(zhuǎn)為字符串,如果 ab > ba,則a排在前面,比如9和34,由于 934>349,所以9排在前面,再比如說 30 和3,由于 303<330,所以3排在 30 的前面。按照這種規(guī)則對原數(shù)組進行排序后,將每個數(shù)字轉(zhuǎn)化為字符串再連接起來就是最終結(jié)果。代碼如下:
class Solution { public: string largestNumber(vector<int>& nums) { string res; sort(nums.begin(), nums.end(), [](int a, int b) { return to_string(a) + to_string(b) > to_string(b) + to_string(a); }); for (int i = 0; i < nums.size(); ++i) { res += to_string(nums[i]); } return res[0] == '0' ? "0" : res; } };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/179
參考資料:
https://leetcode.com/problems/largest-number/
https://leetcode.com/problems/largest-number/discuss/53158/My-Java-Solution-to-share
https://leetcode.com/problems/largest-number/discuss/53157/A-simple-C%2B%2B-solution
到此這篇關(guān)于C++實現(xiàn)LeetCode(179.最大組合數(shù))的文章就介紹到這了,更多相關(guān)C++實現(xiàn)最大組合數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++基于QWidget和QLabel實現(xiàn)圖片縮放,拉伸與拖拽
這篇文章主要為大家詳細介紹了C++如何基于QWidget和QLabel實現(xiàn)圖片縮放、拉伸與拖拽等功能,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-02-02C++實現(xiàn)LeetCode(557.翻轉(zhuǎn)字符串中的單詞之三)
這篇文章主要介紹了C++實現(xiàn)LeetCode(557.翻轉(zhuǎn)字符串中的單詞之三),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-08-08