服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - C++实现LeetCode(179.最大组合数)

C++实现LeetCode(179.最大组合数)

2021-12-10 15:02Grandyang C/C++

这篇文章主要介绍了C++实现LeetCode(179.最大组合数),本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下

[LeetCode] 179. Largest Number 最大组合数

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.

这道题给了我们一个数组,让将其拼接成最大的数,那么根据题目中给的例子来看,主要就是要给数组进行排序,但是排序方法不是普通的升序或者降序,因为9要排在最前面,而9既不是数组中最大的也不是最小的,所以要自定义排序方法。如果不参考网友的解法,博主估计是无法想出来的。这种解法对于两个数字a和b来说,如果将其都转为字符串,如果 ab > ba,则a排在前面,比如9和34,由于 934>349,所以9排在前面,再比如说 30 和3,由于 303<330,所以3排在 30 的前面。按照这种规则对原数组进行排序后,将每个数字转化为字符串再连接起来就是最终结果。代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
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

到此这篇关于C++实现LeetCode(179.最大组合数)的文章就介绍到这了,更多相关C++实现最大组合数内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/grandyang/p/4225047.html

延伸 · 阅读

精彩推荐