随笔- 509  文章- 0  评论- 151  阅读- 22万 

Largest Number

2015.1.23 20:24

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 is 9534330.

Note: The result may be very large, so you need to return a string instead of an integer.

Solution:

  Sort the numbers and piece them together, you'll get the answer, either largest or smallest. As for how to sort them, please see the comparator().

  Time complexity is O(n * log(n)), space complexity may be the same, or less.

Accepted code:

复制代码
 1 //#define ZZ
 2 #include <algorithm>
 3 #include <cstdio>
 4 #include <iostream>
 5 #include <string>
 6 #include <vector>
 7 using namespace std;
 8 
 9 bool comparator(const string &s1, const string &s2)
10 {
11     string s12, s21;
12 
13     s12 = s1 + s2;
14     s21 = s2 + s1;
15 
16     bool res = s12 < s21;
17     s12.clear();
18     s21.clear();
19 
20     return res;
21 }
22 
23 class Solution {
24 public:
25     string largestNumber(vector<int> &num) {
26         char s[100];
27         vector<string>vs;
28 
29         int n, i;
30 
31         n = (int)num.size();
32         for (i = 0; i < n; ++i) {
33             sprintf(s, "%d", num[i]);
34             vs.push_back(string(s));
35         }
36 
37         sort(vs.begin(), vs.end(), comparator);
38         string res = "";
39 
40         for (i = n - 1; i >= 0; --i) {
41             res += vs[i];
42         }
43         vs.clear();
44 
45         i = 0;
46         n = (int)res.length();
47         while (i < n - 1 && res[i] == '0') {
48             ++i;
49         }
50         res = res.substr(i, n - i);
51 
52         return res;
53     }
54 };
55 
56 #ifdef ZZ
57 int main()
58 {
59     vector<int> num;
60     int n;
61     int i;
62     Solution sol;
63 
64     while (cin >> n) {
65         num.resize(n);
66         for (i = 0; i < n; ++i) {
67             cin >> num[i];
68         }
69         cout << sol.largestNumber(num) << endl;
70         num.clear();
71     }
72 
73     return 0;
74 }
75 #endif
复制代码

 

 posted on   zhuli19901106  阅读(310)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示