128 Largest Number (自定义比较函数排序)
来源:互联网 发布:java开发流程图 编辑:程序博客网 时间:2024/06/07 04:54
Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9]
, the largest formed number is9534330
.
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.
Subscribe to see which companies asked this question
本题的关键在于写出sort函数的自定义排序方法,参考[C++]LeetCode: 128 Largest Number (自定义比较函数排序)写的方法,非常的通俗易懂。
对于sort的自定义比较函数
static bool cmp(string a,string b)
{
return a+b>b+a;
}
当需要a排前面,b排后面返回true,若需要b排前面,a排后面则需要返回false.显然上面是要a+b比b+a大时把a排前面。
bool less_int(int a,int b){
return b<a;
}
显然上面是a>b时,a排前面。即按大到小的排。bool less_int(int a,int b){
return b>a;
}
按小到大的排。代码:
class Solution {
public:
static bool cmp(string a,string b)
{
return a+b>b+a;
}
string largestNumber(vector<int>& nums) {
vector<string> v1;
for(auto p:nums)
v1.push_back(to_string(p));
sort(v1.begin(),v1.end(),cmp);
string result="";
for(auto p:v1)
result+=p;
if(result[0]=='0') return "0";
return result;
}
};
- 128 Largest Number (自定义比较函数排序)
- [C++]LeetCode: 128 Largest Number (自定义比较函数排序)
- leetcode 179 Largest Number (sort自定义比较函数用法)
- LeetCode Largest Number(排序)
- 01串排序。自定义比较仿函数
- C#排序函数和自定义比较器
- LeetCode Largest Number JAVA 快速排序
- stl排序函数用户自定义比较函数扩展
- Largest Number
- Largest Number
- Largest Number
- Largest Number
- Largest Number
- Largest Number
- Largest Number
- Largest Number
- Largest Number
- Largest Number
- Atitit.判断汉字的编码 regedit 注册表里面的reg_sz
- windows下如何删除需要***授权的文件夹、文件
- C语言练习1
- Win7 下安装与使用Curl
- 正则表达式基础入门学习http://deerchao.net/tutorials/regex/regex.htm
- 128 Largest Number (自定义比较函数排序)
- sql求解两个时间差
- 【计服15】实验三参考代码
- DFS与BFS的区别、用法、详解?
- centos7安装后windows启动菜单修复
- poj 1269 Intersecting Lines
- 利用Disk Genius分区工具给电脑硬盘进行分区详细图文教程
- 基于Solr的空间搜索学习笔记
- Android程序去除标题栏