码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode:Largest Number(Greedy)

时间:2015-07-08 17:51:23      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

problem:

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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

解决思路:这个属于贪心问题。获得拼接最大的数,里面包含两个数拼接最大的子问题。所以采用逐一拼接。要考虑到特殊情况,首数为0的问题。

问题归结为比较两个字符串拼接问题 s1+s2>s2+s1

 1 class Solution {
 2 public:
 3     string largestNumber(vector<int>& nums) {
 4         
 5         vector<string> strarr;
 6         
 7         for(int num:nums)
 8             strarr.push_back(to_string(num));
 9         sort(strarr.begin(),strarr.end(),compare);
10         
11         string result;
12         for(string str:strarr)
13             result+=str;
14             
15         if(result[0] == 0 && result.size() > 0) 
16             return "0";
17             
18         return result;
19     }
20 
21 private:
22     //自定义比较函数 
23     static bool compare(string &s1, string &s2)
24     {
25         return s1 + s2 > s2 + s1;
26     }
27 };

 

LeetCode:Largest Number(Greedy)

标签:

原文地址:http://www.cnblogs.com/xiaoying1245970347/p/4630613.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!