LeetCode:Largest Number(Greedy)

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 };

 

posted @ 2015-07-08 16:33  尾巴草  阅读(195)  评论(0编辑  收藏  举报