Largest Number

来源:互联网 发布:数据图表制作软件 编辑:程序博客网 时间:2024/04/28 05:26

Largest Number

leetcode sort


原题链接 
参考 - Cindy_niu


题意

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

思路:

1 对于两个备选数字a和b, 如果str(a) + str(b) > str(b) + str(b), 则a在b之前,否则b在a之前,按照这个原则对原数组从大到小排序即可。我们只需要写出sort函数的自定义比较函数即可,注意的是,这里比较函数必须为静态函数。还有我们,要注意一个特殊情况,如果字符串后的字符串从0开始,我们返回“0”。

2 首先,我们将num转成字符串存入数组,然后根据自定义比较函数排序,之后再对排序后的字符串连接成一个字符串,最后排除特殊情况,得到所求结果。

注意:

1 注意特殊情况,如果字符串开头含0,最后返回“0”

2 sort中的比较函数compare要声明为静态成员函数或全局函数,不能作为普通成员函数,否则会报错. Line 26: invalid use of non-static member function

因为:非静态成员函数是依赖于具体对象的,而std::sort这类函数是全局的,因此无法再sort中调用非静态成员函数。静态成员函数或者全局函数是不依赖于具体对象的, 可以独立访问,无须创建任何对象实例就可以访问。同时静态成员函数不可以调用类的非静态成员。

code

  1. class Solution {
  2. public:
  3. string largestNumber(vector<int> &num) {
  4. vector<string>res;
  5. for(int i = 0; i < num.size(); i++) {
  6. //if(num[i] == 0) {
  7. // res.push_back("0");
  8. // continue;
  9. //}
  10. //string r;
  11. //IntToString(num[i], r);
  12. //res.push_back(r);
  13. res.push_back(to_string(num[i]));
  14. }
  15. sort(res.begin(), res.end(), cmp);
  16. string s;
  17. for(int i = 0; i < res.size(); i++) {
  18. s += res[i];
  19. }
  20. // special case, since arranged by descending order,
  21. // just judge the first element of res is "0",
  22. if(res[0] == "0") return "0";
  23. return s;
  24. }
  25. void IntToString(int num, string& res) {
  26. if(num == 0) return;
  27. IntToString(num / 10, res);
  28. res += (num % 10) + '0';
  29. }
  30. private:
  31. static bool cmp(const string& a, const string& b) {
  32. return a + b > b + a;
  33. }
  34. };
0 0
原创粉丝点击