面試題45:把陣列排成最小的數
阿新 • • 發佈:2020-08-19
輸入一個正整數陣列,把數組裡所有數字拼接起來排成一個數,列印能拼接出的所有數字中最小的一個。例如輸入陣列{3,32,321},則打印出這三個數字能排成的最小數字為321323。
解題思路
- 回溯法(較暴力)
- 重新定義比較數字函式(較高階)
上程式碼(C++香)
法一,回溯法遞迴出全排列
#include <iostream> #include <vector> #include <stack> #include <string> #include <cstring> #include <queue> #include <algorithm> #include <stdlib.h> #include "TreeNode.h" using namespace std; string minS = "99999999"; void mySwap(vector<int> &num, int i, int j){ int temp = num[j]; num[j] = num[i]; num[i] = temp; } bool isSwap(vector<int> num, int index, int n){ for(int i = index + 1; i < n; i++){ if(num[i] == num[index]) return false; } return true; } void dfs(vector<int> &num, int index, int n){ if(index == n){ string nowS; for(int i = 0; i < n; i++) nowS = nowS + to_string(num[i]); if(nowS < minS) minS = nowS; return ; } for(int i = index; i < n; i++){ if(isSwap(num, i, n)){ mySwap(num, i, index); dfs(num, index + 1, n); mySwap(num, i, index); } } } // 使用全排列來判斷 string PrintMinNumber(vector<int> numbers) { dfs(numbers, 0, numbers.size()); return minS; } int main() { vector<int> num; num.push_back(3); num.push_back(32); num.push_back(321); cout<<PrintMinNumber(num)<<endl; return 0; }
法二:重新定義數字的比較函式
比如數字3與32,因為323<332,所以32<3。
#include <iostream> #include <vector> #include <stack> #include <string> #include <cstring> #include <queue> #include <algorithm> #include <stdlib.h> #include "TreeNode.h" using namespace std; const int g_MaxNumberLength = 10; char* g_StrCombine1 = new char[g_MaxNumberLength * 2 + 1]; char* g_StrCombine2 = new char[g_MaxNumberLength * 2 + 1]; // 重新定義數字比較函式 int 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 PrintMinNumber(int numbers[], int length){ if(length <= 0) return ; char** strNumbers = (char**)(new int[length]); 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]); printf("\n"); for(int i = 0; i < length; i++) delete[] strNumbers[i]; delete[] strNumbers; } int main() { int num[] = {3,32,321}; PrintMinNumber(num, 3); return 0; }