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 };
  • 相关阅读:
    Spring +quartz获取ApplicationContext上下文
    开源 java CMS
    js实现页面跳转的几种方式
    hdu-4089-Activation-概率dp
    linux 内核定时器
    linux 短延时
    linux 基于 jiffy 的超时
    linux 让出处理器
    linux 延后执行
    linux获知当前时间
  • 原文地址:https://www.cnblogs.com/xiaoying1245970347/p/4630613.html
Copyright © 2011-2022 走看看