(C++)剑指offer-32:把数组排成最小的数(时间效率)

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

目录

1题目描述

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

2题目解析

sort()函数

STL中就自带了排序函数sort对给定区间所有元素进行排序
要使用此函数只需用 #include < algorithm> 头文件

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

int main()
{
    int i=0;
    int a[10]={2,4,1,23,5,76,0,43,24};

    for(i=0;i<10;i++)
        cout<<a[i]<<" ";
    cout<<endl;

    sort(a,a+10);

    for(i=0;i<10;i++)
        cout<<a[i]<<" ";
    cout<<endl;
}

2 4 1 23 5 76 0 43 24 0
0 0 1 2 4 5 23 24 43 76

输出结果将是把数组a按升序排序,说到这里可能就有人会问怎么样用它降序排列呢?

这就是下一个讨论的内容,一种是自己编写一个比较函数来实现,接着调用三个参数的sort
sort(begin,end,compare)就成了

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

bool cmp(int a,int b)
{
  return a>b; //降序排列,如果改为return a<b,则为升序
}

int main()
{
    int i=0;
    int a[10]={2,4,1,23,5,76,0,43,24};

    for(i=0;i<10;i++)
        cout<<a[i]<<" ";
    cout<<endl;

    sort(a,a+10,cmp);

    for(i=0;i<10;i++)
        cout<<a[i]<<" ";
    cout<<endl;
}

2 4 1 23 5 76 0 43 24 0
76 43 24 23 5 4 2 1 0 0

3题目答案

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

sort中的比较函数compare要声明为静态成员函数或全局函数,不能作为普通成员函数,否则会报错。 因为:非静态成员函数是依赖于具体对象的,而std::sort这类函数是全局的,因此无法再sort中调用非静态成员函数。静态成员函数或者全局函数是不依赖于具体对象的, 可以独立访问,无须创建任何对象实例就可以访问。同时静态成员函数不可以调用类的非静态成员。

4完整代码

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

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> v={3, 32, 321};
   Solution s;
   cout<<s.PrintMinNumber(v)<<endl;
}

321323

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值