当前位置:网站首页>【剑指offer】面试题45:把数组排成最小的数
【剑指offer】面试题45:把数组排成最小的数
2022-07-27 14:24:00 【Jocelin47】

1.高位的数字肯定是越小越好
2.放数字的顺序肯定是先放第一位(最左边一位)最小的元素,如果第一位相等,比较第二位…,以此类推。
3.我们如果把所有数字转换成字符串再排列
4.对所有的字符串进行比较
5.两个字符串s1,s2 如果 s1+ s2 > s2 + s1那么s1 > s2
比如s1为3,s2为30,因为 s1+s2 = 330 ,s2+s1 = 303,所以s1 > s2
我们因此可以自己定义字符串比较规则:
static bool compare(string &s1, string &s2)
{
return s1 + s2 < s2 + s1;
}
通过lambda表达式去写也可以。
代码如下:
class Solution {
public:
string minNumber(vector<int>& nums) {
vector<string> strs;
string result;
for( int i = 0; i < nums.size(); i++)
{
strs.push_back(to_string(nums[i]));
}
sort(strs.begin(), strs.end(), [](string &s1, string &s2) {
return s1 + s2 < s2 + s1;} );
//sort(strs.begin(), strs.end(), compare);
for( int i = 0; i < strs.size(); i++ )
{
result += strs[i];
}
return result;
}
// static bool compare(string &s1, string &s2)
// {
// return s1 + s2 < s2 + s1;
// }
};
组成最大的数
https://www.nowcoder.com/questionTerminal/fc897457408f4bbe9d3f87588f497729
边栏推荐
- 【剑指offer】面试题51:数组中的逆序对——归并排序
- Leetcode 90. subset II backtracking /medium
- Pytorch replaces some components in numpy. / / please indicate the source of the reprint
- Network equipment hard core technology insider router Chapter 13 from deer by device to router (Part 1)
- Several basic uses of tl431-2.5v voltage reference chip
- Is it safe to open an account on a mobile phone?
- Unity性能优化------渲染优化(GPU)之Occlusion culling(遮挡剔除)
- 修改 Spark 支持远程访问OSS文件
- Dan bin Investment Summit: on the importance of asset management!
- 微信公众平台开发概述
猜你喜欢

How to take satisfactory photos / videos from hololens

华云数据打造完善的信创人才培养体系 助力信创产业高质量发展

Spark 任务Task调度异常分析

generic paradigm

适配验证新职业来了!华云数据参与国家《信息系统适配验证师国家职业技能标准》编制

reflex

初探JuiceFS

西瓜书《机器学习》阅读笔记之第一章绪论

/dev/loop1占用100%问题

Leetcode interview question 17.21. water volume double pointer of histogram, monotonic stack /hard
随机推荐
Unity3d learning note 10 - texture array
js使用for in和for of来简化普通for循环
TL431-2.5v基准电压芯片几种基本用法
Spark 任务Task调度异常分析
Leetcode 81. search rotation sort array II binary /medium
Leetcode 1143. dynamic programming of the longest common subsequence /medium
Introduction of the connecting circuit between ad7606 and stm32
Network equipment hard core technology insider router 19 dpdk (IV)
学习Parquet文件格式
Reading notes of lifelong growth (I)
Discussion on STM32 power down reset PDR
适配验证新职业来了!华云数据参与国家《信息系统适配验证师国家职业技能标准》编制
Network equipment hard core technology insider router Chapter 18 dpdk and its prequel (III)
使用解构交换两个变量的值
Leetcode 781. rabbit hash table in forest / mathematical problem medium
Pictures to be delivered
/dev/loop1占用100%问题
AssetBundle如何打包
STM32F10x_ Hardware I2C read / write EEPROM (standard peripheral library version)
【剑指offer】面试题52:两个链表的第一个公共节点——栈、哈希表、双指针