zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    Linux下安装FTP服务(Ubuntu)
    Ubuntu下无法使用Secure_CRT连接服务器
    Mysql 锁机制
    PHP提取HTML代码中img标签下src属性
    Mysql 隐式转换
    PHPExcel在TP下使用
    ThinkPHP同时操作多个数据库
    PHP 时间相关操作
    ThinkPHP输入验证和I方法使用
    ThinkPHP模板内使用U方法
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/5805256.html
Copyright © 2011-2022 走看看