zoukankan      html  css  js  c++  java
  • Leetcode 179 Largest Number 贪心

    此题主要是讲给你一组数,如何将数连在一起能得到最大值(最小值反之),注意局部最优,就是说如果 123 234两个连在一起怎么样最大,显然是234123比123234大,对于3个数我们可以找到类似的性质,4个数一样。。。因此我们得到这个局部最优的排序是全局最优的。因此这个实现最核心的代码就是函数cmp,其他的就是要注意全是0的情况和前导0的情况,这题就轻松解决。

     1 inline bool cmp(const std::string &a, const std::string &b)
    {
    2 return a + b > b + a; 3 } 4 class Solution 5 { 6 public: 7 Solution() = default; 8 ~Solution() = default; 9 inline std::string inttostr_(int num)
    {
    10 char s[20] = { 0 }; 11 sprintf_s(s,"%d",num); 12 return std::string(s); 13 } 14 15 std::string largestNumber(std::vector<int>& nums)
    {
    16 std::vector<std::string> vstr; 17 for (std::vector<int>::size_type i = 0; i < nums.size(); ++i){ 18 vstr.push_back(inttostr_(nums[i])); 19 } 20 std::sort(vstr.begin(),vstr.end(),cmp); 21 std::vector<std::string>::size_type i = 0; 22 for (; i < nums.size(); ++i){ //删除前导0 23 if (vstr[i] != "0") break; 24 } 25 26 if (i == nums.size()) return "0";//全是0 27 else{ //前导0和其他情况 28 std::string ans(""); 29 for (; i<nums.size(); ++i){ 30 ans += vstr[i]; 31 } 32 return ans; 33 } 34 } 35 };
  • 相关阅读:
    sql.srcipt
    sowmodaldialog
    4) 删除虚拟应用程序
    JavaScript读写Cookies
    第5章 脚本运行期库对象
    npm serve md 工具 [MD]
    cleanmark 清除格式 博客内容提取 [MD]
    Hex编码 十六进制编码
    Windows Server AppFabric(Codename:"Dublin&Velocity")介绍
    WF4设计器模型:编辑范围ModelEditingScope
  • 原文地址:https://www.cnblogs.com/onlyac/p/5130803.html
Copyright © 2011-2022 走看看