《剑指Offer》面试题33:把数组排成最小的数

//面试题33:把数组排成最小的数

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <Windows.h>

using namespace std;

const int prec = numeric_limits<long double>::digits10;

//模板函数:类型转换   
template <typename outType, typename inType>
outType typeConvert(const inType& in)
{
    stringstream ss;
    ss.precision(prec);
    ss << in;
    outType rlt;
    ss >> rlt;
    return rlt;
}

template <typename T> 
inline T& mid(T &a, T &b, T &c)
{
    return min(max(a, b), min(max(a, c), max(b, c)));
}

template <typename T> inline void myswap(T &a, T &b)
{
    T t = a; a = b; b = t;
}

template <typename T> 
int partition(vector<T> &nums, int start, int end, bool (*func)(const string&, const string&))
{
    T& base = mid(nums[start], nums[end], nums[(start + end) >> 1]);
    myswap(base, nums[end]);

    int i = start;
    for (int j = start; j < end; j++)
    {
        if (func(nums[j], nums[end]))
        {
            if (nums[i] != nums[j])
                myswap(nums[i], nums[j]);
            i++;
        }
    }
    myswap(nums[i], nums[end]);
    return i;
}

template <typename T> 
void quickSort(vector<T> &nums, int start, int end, bool (*func)(const string&, const string&))
{
    if (nums.empty() || start >= end)
        return;

    int mid = partition(nums, start, end, func);
    if (mid > start)
        quickSort(nums, start, mid - 1, func);
    if (mid < end)
        quickSort(nums, mid + 1, end, func);
}

template <typename T> 
void quickSort(vector<T> &nums, bool (*func)(const string&, const string&))
{
    if (nums.empty())
        return;

    quickSort(nums, 0, nums.size() - 1, func);
}

template <typename T> 
void printArr(const vector<T> &nums, const string &sep)
{
    for (int i = 0; i < nums.size(); i++)
    {
        cout << nums[i] << sep;
    }
    cout << endl;
}

bool compareString(const string &a, const string &b)
{
    return (a + b) < (b + a);
}

void printMinNum(const vector<int> &nums)
{
    vector<string> rlt;
    for (int i = 0; i < nums.size(); i++)
        rlt.push_back(typeConvert<string>(nums[i]));

    quickSort(rlt, compareString);

    printArr(rlt, "");
}

int main()
{
    cout.precision(prec);

    vector<int> nums = { 1, 12, 123, 1234, 12345 };
    vector<int> nums1 = { 3, 32, 321 };

    printMinNum(nums);
    printMinNum(nums1);

    system("pause");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值