• Largest Number


    Given a list of non negative integers, arrange them such that they form the largest number.

    Notice

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

    Example

    Given [1, 20, 23, 4, 8], the largest formed number is8423201.

    Analyse: to determine how to place a, b, we could combine a and b in string way and compare to_string(a) + to_string(b), to_string(b) + to_string(a).  Aftersorting, it could be 00000008 or 0000000, we need to check whether there is consecutive 0s in the highest index. Lambda is used to sort self-defined comparator. 

    Runtime: 20ms.

     1 class Solution {
     2 public:
     3     /**
     4      *@param num: A list of non negative integers
     5      *@return: A string
     6      */
     7     string largestNumber(vector<int> &num) {
     8         // write your code here
     9         string result;
    10         if (num.empty()) return result;
    11         sort(num.begin(), num.end(), [](int a, int b) {
    12             // regard a, b as string, append b to a and a to b
    13             // compare a + b and b + a
    14             string ab = to_string(a) + to_string(b);
    15             string ba = to_string(b) + to_string(a);
    16             return ab < ba;
    17         });
    18         int i = num.size() - 1;
    19         while (i >= 0 && !num[i]) i--;
    20         while (i >= 0)
    21             result += to_string(num[i--]);
    22         return result.empty() ? "0" : result;
    23     }
    24 };
  • 相关阅读:
    js 遍历数组对象求和
    小程序使用微信地址or小程序跳转设置页
    css内容渐入效果实现
    flutter实现文字超出最大宽度显示省略号
    flutter查看安全码SHA1
    Uncaught (in promise)
    小程序iphone蒙层滚动穿透
    map中使用箭头函数遇到的坑
    骨架屏css样式
    javascript(js)反转字符串
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/5805256.html
Copyright © 2020-2023  润新知