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 };

      

  • 相关阅读:
    [读书计划]2015读书计划
    [整理]iOS开发学习
    nginx配置
    Nginx的使用
    Spring
    JSP的使用以及EL和JSTL的使用
    关于linux安装tomcat和mysql
    linux常用操作(安装jdk配置环境变量)
    redis的安装与使用
    Mybatis
  • 原文地址:https://www.cnblogs.com/wangshujing/p/6941861.html
Copyright © 2011-2022 走看看