zoukankan      html  css  js  c++  java
  • 剑指Offer——把数组排成最小的数

    题目描述:

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


    分析:

     排序的变形。

    自定义比较函数:

    比较3和32:

    将3和32拼接在一起为332,将32和3拼接在一起为323,比较这两个数的大小332>323,那么32应该排在3的前面。

    其他数类似。。


    代码:

     1 class Solution {
     2 public:
     3     string PrintMinNumber(vector<int> numbers) {
     4         int numSize = numbers.size();
     5         string s;
     6         if(numSize == 0) return s;
     7         sort(numbers.begin(), numbers.end(), cmp);
     8         for(int i = 0; i < numSize; i++) {
     9             s += to_string(numbers[i]);
    10         }
    11         return s;
    12     }
    13     static bool cmp(int a, int b) {
    14         string a2s = to_string(a);
    15         string b2s = to_string(b);
    16         string s1 = a2s + b2s;
    17         string s2 = b2s + a2s;
    18         return s1 < s2;
    19     }
    20 };
  • 相关阅读:
    Java编译器API简介
    liblinear和libsvm区别
    spark和hadoop比较
    maxout激活函数
    FTRL算法
    NLP里面好的学习资料
    阿里妈妈MLR模型(论文)
    FM的推导原理--推荐系统
    GBDT+LR simple例子
    深度学习最全优化方法---来源于知乎
  • 原文地址:https://www.cnblogs.com/jacen789/p/7747668.html
Copyright © 2011-2022 走看看