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

    剑指offer-把数组排成最小的数

     

    题目描述

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

    题解:

        利用sort函数的cmp功能,实现将组合成的数字最小到最大的方式排列

    bool Cmp(int a, int b){
        int a_num = 0, b_num = 0, at = a, bt = b;
        while(at){
            a_num++; 
            at /= 10; 
        }
        while(bt){
            b_num++; 
            bt /= 10; 
        }
        at = b*pow(10, a_num) + a; 
        bt = a*pow(10, b_num) + b; 
        return bt < at; 
    }
    
    class Solution {
    public:
        string PrintMinNumber(vector<int> numbers) {
            sort(numbers.begin(), numbers.end(), Cmp); 
            string ans = ""; 
            for(int i=0; i<numbers.size(); ++i){
                ans += to_string(numbers[i]); 
            }
            return ans; 
        }
    };
    

      

  • 相关阅读:
    POJ 1017
    poj 2709
    poj 1328
    POJ 2386
    POJ 1065
    POJ 3728
    hdu--1004--Let the Balloon Rise
    hdu--2570--迷瘴(贪心)
    hdu--1257--最少拦截系统(贪心)
    hdu--1230--火星A+B
  • 原文地址:https://www.cnblogs.com/zhang-yd/p/6607548.html
Copyright © 2011-2022 走看看