zoukankan      html  css  js  c++  java
  • 剑指offer之【把数组排成最小的数】☆

    题目:

      把数组排成最小的数

    链接;

      https://www.nowcoder.com/practice/8fecd3f8ba334add803bf2a06af1b993?tpId=13&tqId=11185&tPage=2&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

    题目描述:

      输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。

    思路:

      首先是数字转化成字符串,然后进行一个字典序的排序,最后把字符串链接起来

    代码:

      

     1 class Solution {
     2 public:
     3     string PrintMinNumber(vector<int> numbers){
     4         int len = numbers.size();
     5         if(len <= 0)
     6               return res;
     7         vector<string> snums;
     8         for(int x:numbers){                    // 将数字转换为字符串
     9             stringstream ss;
    10             ss << x;
    11             snums.push_back(ss.str());
    12         }
    13         sort(snums.begin(),snums.end(),compare);   //  字典序排序
    14 
    15         for(auto it = snums.begin();it != snums.end();++it){  //  字符串链接起来
    16             res.append(*it);
    17         }
    18         return res;
    19     }
    20     static bool compare(const string &str1, const string &str2){
    21         string s1 = str1+str2;
    22         string s2 = str2+str1;
    23         return s1 < s2;
    24     }
    25 private:
    26     string res;
    27 };

      

  • 相关阅读:
    BZOJ 3924: [Zjoi2015]幻想乡战略游戏
    codevs 4244 平衡树练习
    BZOJ 2002: [Hnoi2010]Bounce 弹飞绵羊
    BZOJ 2038: [2009国家集训队]小Z的袜子
    luogu P3709 大爷的字符串题
    BZOJ 2120: 数颜色
    luogu P2056 采花
    luogu P2709 小B的询问
    BZOJ 1878: [SDOI2009]HH的项链
    Codeforces 221d D. Little Elephant and Array
  • 原文地址:https://www.cnblogs.com/wangshujing/p/6941861.html
Copyright © 2011-2022 走看看