leetcode.179.最大数(largest-number)

179 篇文章 0 订阅
21 篇文章 1 订阅

179.最大数

给定一组非负整数 nums,重新排列每个数的顺序(每个数不可拆分)使之组成一个最大的整数。

**注意:**输出结果可能非常大,所以你需要返回一个字符串而不是整数。

示例 1:

输入:nums = [10,2]
输出:"210"

示例 2:

输入:nums = [3,30,34,5,9]
输出:"9534330"

示例 3:

输入:nums = [1]
输出:"1"

示例 4:

输入:nums = [10]
输出:"10"

提示:

  • 1 <= nums.length <= 100 100 100
  • 0 <= nums[i] <= 1 0 9 10^{9} 109

代码与思路

大概思路就是比较两个数,依次比较他们的最高位,如果最高位相同,比较次高位。(两个数位数不一样可以比较吗,也是可以的,比如[45,123],4大于1,所以45放前面),这种排序对于输入数组没有相同数字开头的时候是有效的,比如{ 45,56,81,76,123 };81765645123
输入数组有相同数字开头的情况:
[4,42]比较,442>424,所以要把4放在前面;
[4,45]比较,454>445,所以要把45放在前面。
两个数字比较后,相对位置的关系就知道了,没有必要进行全排列比较。

#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
#include <numeric>

using namespace std;

class Solution {
public:
	string largestNumber(vector<int>& nums) {
		vector<string> vs;
		transform(nums.begin(), nums.end(), back_inserter(vs), [](int x) {return to_string(x); });// algorithm---transform
		sort(vs.begin(), vs.end(), [](const string& a, const string& b) {
			return a + b > b + a;
			});
		string res = accumulate(vs.begin(), vs.end(), string());//  numeric---accumulate
		return res[0] == '0' ? "0" : res;
	}
	string largestNumber2(vector<int>& nums) {
		// 将 nums 中的元素按照如下示例规则排序:
		// 因 "2" + "10" > "10" + "2" , 故 2 排在 10 的前面 
		sort(nums.begin(), nums.end(), [](int x, int y) {
			string a = to_string(x), b = to_string(y);
			return a + b > b + a;
		});
		// 将排序后的数组转为字符串
		string ans = "";
		for (int n : nums) ans += to_string(n);
		// 输入为 [0,0] 时,输出应该为 "0"
		return ans[0] == '0' ? "0" : ans;
	}
};

int main()
{
	int nums[] = { 3,30,34,5,9 };
	vector<int> v(nums, nums + 5);
	for (auto it : v)
	{
		cout << it << endl;
	}
	Solution s;
	cout << s.largestNumber(v) << endl;
}

参考

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值