• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

c++ 搞代码 4年前 (2022-01-06) 38次浏览 已收录 0个评论
文章目录[隐藏]

这篇文章主要介绍了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 的前面。按照这种规则对原数组进行排序后,将每个数字转化为字符串再连接起来就是最终结果。代码如下:

 cl<mark style="color:transparent">来源gaodaimacom搞#^代%!码网</mark>ass Solution { public: string largestNumber(vector& 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.最大组合数)的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:C++实现LeetCode(179.最大组合数)

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址