1. 程式人生 > >《劍指offer》第四十五題(把數組排成最小的數)

《劍指offer》第四十五題(把數組排成最小的數)

delete pre \n 例如 nbsp strcpy 有一個 expec expect

// 面試題45:把數組排成最小的數
// 題目:輸入一個正整數數組,把數組裏所有數字拼接起來排成一個數,打印能拼
// 接出的所有數字中最小的一個。例如輸入數組{3, 32, 321},則打印出這3個數
// 字能排成的最小數字321323。

#include <iostream>
#include <string>
#include <algorithm>

int compare(const void* strNumber1, const void* strNumber2);

// int型整數用十進制表示最多只有10位
const int g_MaxNumberLength = 10
; char* g_StrCombine1 = new char[g_MaxNumberLength * 2 + 1]; char* g_StrCombine2 = new char[g_MaxNumberLength * 2 + 1]; void PrintMinNumber(const int* numbers, int length) { if (numbers == nullptr || length <= 0) return; char** strNumbers = (char**)(new int[length]);//通過下面這個循環,把number裏的每個數字,轉化為strNumbers的二維數組中,註意**
for (int i = 0; i < length; ++i) { strNumbers[i] = new char[g_MaxNumberLength + 1]; sprintf(strNumbers[i], "%d", numbers[i]); } qsort(strNumbers, length, sizeof(char*), compare);//快排函數,詳見博客 for (int i = 0; i < length; ++i) printf("%s", strNumbers[i]);//
將排序好的strNumbers逐個元素打印出來,即最小值 printf("\n"); for (int i = 0; i < length; ++i) delete[] strNumbers[i];//逐個刪除 delete[] strNumbers; } // 如果[strNumber1][strNumber2] > [strNumber2][strNumber1], 返回值大於0 // 如果[strNumber1][strNumber2] = [strNumber2][strNumber1], 返回值等於0 // 如果[strNumber1][strNumber2] < [strNumber2][strNumber1], 返回值小於0 int compare(const void* strNumber1, const void* strNumber2)//qsort的第四個參數,cmp函數,詳見博客 { // [strNumber1][strNumber2] strcpy(g_StrCombine1, *(const char**)strNumber1); strcat(g_StrCombine1, *(const char**)strNumber2); // [strNumber2][strNumber1] strcpy(g_StrCombine2, *(const char**)strNumber2); strcat(g_StrCombine2, *(const char**)strNumber1); return strcmp(g_StrCombine1, g_StrCombine2); } // ====================測試代碼==================== void Test(const char* testName, int* numbers, int length, const char* expectedResult) { if (testName != nullptr) printf("%s begins:\n", testName); if (expectedResult != nullptr) printf("Expected result is: \t%s\n", expectedResult); printf("Actual result is: \t"); PrintMinNumber(numbers, length); printf("\n"); } void Test1() { int numbers[] = { 3, 5, 1, 4, 2 }; Test("Test1", numbers, sizeof(numbers) / sizeof(int), "12345"); } void Test2() { int numbers[] = { 3, 32, 321 }; Test("Test2", numbers, sizeof(numbers) / sizeof(int), "321323"); } void Test3() { int numbers[] = { 3, 323, 32123 }; Test("Test3", numbers, sizeof(numbers) / sizeof(int), "321233233"); } void Test4() { int numbers[] = { 1, 11, 111 }; Test("Test4", numbers, sizeof(numbers) / sizeof(int), "111111"); } // 數組中只有一個數字 void Test5() { int numbers[] = { 321 }; Test("Test5", numbers, sizeof(numbers) / sizeof(int), "321"); } void Test6() { Test("Test6", nullptr, 0, "Don‘t print anything."); } int main(int argc, char* argv[]) { Test1(); Test2(); Test3(); Test4(); Test5(); Test6(); system("pause"); return 0; }

《劍指offer》第四十五題(把數組排成最小的數)