zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    个人学习进度(第十二周)
    第一阶段冲刺(第九天)
    搜狗输入法用户体验
    第一阶段冲刺(第八天)
    第一阶段冲刺(第七天)
    Fliter(过滤器)的认识
    一、python运算符
    virtualenv虚拟环境
    Linux命令(二)
    Linux命令(一)
  • 原文地址:https://www.cnblogs.com/xiaoying1245970347/p/4630613.html
Copyright © 2011-2022 走看看