面试题45:把数组排成最小的数(C++)

题目地址:https://leetcode-cn.com/problems/ba-shu-zu-pai-cheng-zui-xiao-de-shu-lcof/

题目描述

输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。

题目示例

示例 1:

输入: [10,2]
输出: "102"

示例 2:

输入: [3,30,34,5,9]
输出: "3033459"

解题思路

分析题目,数组排成最小的数的问题实质上是一个排序问题,所以,需要确定的是排序的规则。因为要排成最小的数,则对于两个数x、y,如果x + y < y + x,则x应该排在y之前;反之,若x + y > y + x,则y应排在x之前,比如x=3,y=30,则x + y = 330,而y + x = 303,基于排序规则可知,30应该排在3的前面,注意这里的x和y均是字符串,x + y实际上是将两个字符串拼接。另外需要注意的一点是排序规则compare必须是static,因为sort()函数的最后一个排序参数是指针,至于为什么呢?首先要明白静态成员函数和非静态成员函数的区别,静态成员函数属于类,非静态成员函数属于对象,非静态成员函数里的参数默认有this指针,但是sort函数里的排序规则,并不需要这个隐形参数,所以,把这个函数设置位static成员函数则没有this指针,参数和普通函数是一样的了。对于sort()函数而言,若compare返回为true,则会将compare的第一个参数放在左边,若compare返回false,则会将compare的第二个参数放在左边。所以,本题的解题步骤如下

  • Step1:利用to_string()方法将arr数组元素转换为字符串数组
  • Step2:使用C++自带排序算法sort()对数组进行排序,sort()函数排序规则我们自定义为s1 + s2 < s2 + s1;
  • Step3:返回最小数的结果

程序源码

class Solution {

public:
    string minNumber(vector<int>& nums) {
        if(nums.size() == 0) return " ";
        string res = "";
        vector<string> arr;
        for(int i = 0; i < nums.size(); i++)
        {
            arr.push_back(to_string(nums[i])); //排序规则compare是string类型,故需要将nums转换成string
        }
        sort(arr.begin(), arr.end(), compare); //compare = [](string s1, string s2){return s1 + s2 < s2 + s1;}
        for(int j = 0; j < arr.size(); j++)
        {
            res += arr[j];
        }
        return res;
    }
     static bool compare(string &s1,string &s2)
        {
            return (s1 + s2 < s2 + s1);
    }
};
/*
static bool compart(string x,string y){
  string s1 = x + y;
  string s2 = y + x;
  return s1 < s2;
}
*/

猜你喜欢

转载自www.cnblogs.com/wzw0625/p/12813735.html