剑指offer 面试题33 把数组排成最小的数

  题目链接: 剑指offer

  题目链接: 把数组排成最小的数, 例如{3, 32, 321} 输出: 321323

  解题思路: 我现在已经知道正确答案了, 就是没有办法去证明, 先去开会, 在开会的时候再去想。

  代码: 

#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <cstring>
#include <iterator>
#include <cmath>
#include <algorithm>
#include <stack>
#include <deque>
#include <map>
#include <set>
#include <queue>
#define lson l, m, rt<<1
#define rson m+1, r, rt<<1|1
#define mem0(a) memset(a,0,sizeof(a))
#define mem1(a) memset(a,-1,sizeof(a))
#define sca(x) scanf("%d",&x)
#define de printf("=======
")
typedef long long ll;
using namespace std;

const int g_MaxNumberLength = 10;

char * g_StrCombine1 = new char[2*g_MaxNumberLength+1];
char * g_StrCombine2 = new char[2*g_MaxNumberLength+2];

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( numbers == NULL || length <= 0 ) return;
    char **strNumbers = (char **)(new int[length]);
    for( int i = 0; i < length; i++ ) {
        strNumbers[i] = (char *)(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( "
" );
    for( int i = 0; i < length; i++ ) {
        delete [] strNumbers[i];
    }
    delete [] strNumbers;
}

int main() {
    int data[4] = {3, 321, 32};
    PrintMinNumber(data, 3);
    return 0;
}
View Code

  思考: 自己还想了一种做法, 并且证明了正确性。 我们现在的目的就是要重新要排序这个数组, 对于两个数我们怎么判断谁优呢, 我们一位一位去比较, 如果某个数比某个数打了很明显就是小的那个数优,但是对于一个串是另个串的前缀呢? 我们这个时候就应该分类讨论了,  32 要 优于 3,   3 要优于 34, 为什么呢, 我们这里只需要考虑数大于的情况, 因为小的一定已经排到前面去了, 哎呀.....表达不清楚

原文地址:https://www.cnblogs.com/FriskyPuppy/p/7516647.html