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

      

  • 相关阅读:
    反射学习笔记
    路由机制
    缓存笔记
    进程和线程
    垃圾回收机制
    堆和栈
    值类型和引用类型及参数传递
    招到一个程序员很难吗?
    全面讲解:委托、事件
    struts2入门实例
  • 原文地址:https://www.cnblogs.com/wangshujing/p/6941861.html
Copyright © 2011-2022 走看看