[剑指offer]把数组排列成最小的数

/* 33: > 把数组排列成最小的数 {3,32,321} -> 321323 考虑大数问题,开辟 指针数组(str数组) ,每个元素的字符串,存放对应位置的整数(sprintf) 对整个 str数组 进行qsort(需要定制compare) compare: 对于M,N 拼接,比较MN和NM的大小。 */
const int g_MaxNumLen = 10;
char* g_StrCombine1 = new char[g_MaxNumLen * 2 + 1];
char* g_StrCombine2 = new char[g_MaxNumLen * 2 + 1];

int m_Compare(const void* strNumber1, const void* strNumber2)
{
    strcpy(g_StrCombine1,*(const char**)strNumber1);    //二级指针的解引用,确保传参的正确性
    strcat(g_StrCombine1, *(const char**)strNumber2);

    strcpy(g_StrCombine2, *(const char**)strNumber2);
    strcat(g_StrCombine2, *(const char**)strNumber1);

    return strcmp(g_StrCombine1,g_StrCombine2);
}

//
void PrintMinNum(int ar[], int len)
{
    if (ar == NULL || len <= 0)
        return;

    char** strNum = (char**)(new int[len]);
    for (int i = 0; i < len; ++i)
    {
        strNum[i] = new char[g_MaxNumLen+1];
        sprintf(strNum[i],"%d",ar[i]);
    }
    qsort(strNum,len,sizeof(char*),m_Compare);

    for (int i = 0; i < len; ++i)
        cout << strNum[i];
    cout << endl;

    for (int i = 0; i < len; ++i)
        delete[] strNum[i];
    delete[] strNum;
}

//void test()
//{
// int ar[3] = {3,32,321};
// PrintMinNum(ar, 3);
//}

你可能感兴趣的:([剑指offer]把数组排列成最小的数)