leetcode 专题—sort

朱雀 2022-08-08 05:30 232阅读 0赞

此将主要将leetcode中sort专题的解答都放在这里,后续会慢慢加入

一:leetcode179 Largest Number

题目:

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.

分析:这里主要采用stl中的sort函数,注意对与3和33,我们认为其是相等的,另外3要比31大且比34小。最后需要注意的是stl中sort函数对于相等操作要返回false,返回true的话会报异常,警告信息为:

Debug Assertion Failed!
File: c:\program files (x86)\microsoft visual studio
10.0\vc\include\algorithm
Line: 3657
Expression: invalid operator<
调试的时候查看源码就知道了,源码如下:

bool __CLRCALL_OR_CDECL _Debug_lt_pred(_Pr _Pred, _Ty1& _Left, _Ty2& _Right,

const wchar_t *_Where, unsigned int _Line)

{// test if _Pred(_Left, _Right) and _Pred is strict weak ordering

if (!_Pred(_Left, _Right)) // 相等返回true, else if中仍然返回true

return (false);

else if (_Pred(_Right, _Left))

_DEBUG_ERROR2(“invalid operator<”, _Where, _Line);//断言出现在这里。

return (true);

}

代码:

  1. bool cmp(const string &str1, const string &str2){
  2. if(str1 == str2) return false; // 对于STL中的sort 相等不能返回true 看源码就知道了 否则就会报异常
  3. int m = str1.size(), n = str2.size();
  4. int i= 0, j = 0;
  5. while(i < m && j < n){
  6. if(str1[i] < str2[j]) return true;
  7. else if(str1[i] > str2[j]) return false;
  8. else{
  9. if(i+1 == m && j+1 == n) return false; // 这个主要处理比如3 和33的情况 可以认为是相等的
  10. if(i+1 < m)i++;
  11. else i = 0;
  12. if(j+1 < n)j++;
  13. else j = 0;
  14. }
  15. }
  16. return true;
  17. }
  18. class Solution {
  19. public:
  20. string largestNumber(vector<int>& nums) {
  21. // if(nums.size() == 0) return str;
  22. numsStr.resize(nums.size());
  23. for(int i = 0; i < nums.size(); i++){
  24. stringstream ss;
  25. ss << nums[i];
  26. ss >> numsStr[i];
  27. }
  28. sort(numsStr.begin(), numsStr.end(), cmp);
  29. string str;
  30. for(vector<string>::reverse_iterator iter = numsStr.rbegin(); iter != numsStr.rend(); iter++)
  31. str += *iter;
  32. if(str[0] == '0') str = "0";
  33. return str;
  34. }
  35. private:
  36. vector<string> numsStr;
  37. };

发表评论

表情:
评论列表 (有 0 条评论,232人围观)

还没有评论,来说两句吧...

相关阅读

    相关 LeetCode 动态规划专题

    这是整理的LeetCode上的动态规划专题 背包问题 我们将LeetCode上的背包问题进行一个整理,希望之后再遇到以下问题能够快速解决。 组合问题 1. 如

    相关 LeetCode 二分专题

    这是整理的LeetCode上的二分专题,先按照codeTop上的频率顺序从高到低进行整理,然后按别人整理的进行再次整理。 二分搜索概述 先不从具体题来出发,而先从二分查