《剑指offer》面试题——把数组排成最小的数

1.题目描述:

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

2.解题思路:

http://cuijiahua.com/blog/2018/01/basis_32.html
遇到这个题,全排列当然可以做,但是时间复杂度为O(n!)。在这里我们自己定义一个规则,对拼接后的字符串进行比较。

排序规则如下:

若ab > ba 则 a 大于 b,
若ab < ba 则 a 小于 b,
若ab = ba 则 a 等于 b;
根据上述规则,我们需要先将数字转换成字符串再进行比较,因为需要串起来进行比较。比较完之后,按顺序输出即可。

3.代码:

C++:

class Solution {
public:
    string PrintMinNumber(vector<int> numbers) {
        int length = numbers.size();
        if(length == 0){
            return "";
        }
        sort(numbers.begin(), numbers.end(), cmp);
        string res;
        for(int i = 0; i < length; i++){
            res += to_string(numbers[i]);
        }
        return res;
    }
private:
    // 升序排序
    static bool cmp(int a, int b){
        string A = to_string(a) + to_string(b);
        string B = to_string(b) + to_string(a);
        return A < B;
    }
};

Python:

# -*- coding:utf-8 -*-
class Solution:
    def PrintMinNumber(self, numbers):
        # write code here
        if len(numbers) == 0:
            return ''
        compare = lambda a, b:cmp(str(a) + str(b), str(b) + str(a))
        min_string = sorted(numbers, cmp = compare)
        return ''.join(str(s) for s in min_string)

测试代码:

#include<iostream>
#include<algorithm>
using namespace std;

//链接:https://www.nowcoder.com/questionTerminal/8fecd3f8ba334add803bf2a06af1b993
//来源:牛客网

/*对vector容器内的数据进行排序,按照 将a和b转为string后
 若 a+b<b+a  a排在在前 的规则排序,
 如 2 21 因为 212 < 221 所以 排序后为 21 2 
  to_string() 可以将int 转化为string
*/

class Solution
{
    public:
        static bool cmp(int a,int b)
        {
            string A="";
            string B="";
            A+=to_string(a);
            A+=to_string(b);
            B+=to_string(b);
            B+=to_string(a);

            return A<B;
        }
    string PrintMinNumber(vector<int> numbers)
    {
        string answer="";
        sort(numbers.begin(),numbers.end(), cmp);
        for(int i=0;i<numbers.size();i++){
            answer+=to_string(numbers[i]);
        }
        return answer;
    }
};

int main()
{
    vector<int> vec={3,32,321};

    Solution t;

    string ans=t.PrintMinNumber(vec);
    cout<<ans<<endl;
       return 0;
}

猜你喜欢

转载自blog.csdn.net/zhenaoxi1077/article/details/80770232