zoukankan      html  css  js  c++  java
  • 剑指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, 为什么呢, 我们这里只需要考虑数大于的情况, 因为小的一定已经排到前面去了, 哎呀.....表达不清楚

  • 相关阅读:
    选择学习Web前端开发的理由
    在Nginx下部署SSL证书并重定向至HTTPS
    使用pm2快速将项目部署到远程服务器
    DNS域名解析过程
    HTML5新特性总结
    基于 HTML5 Canvas 的智能安防 SCADA 巡逻模块
    react中使用css的7种方式
    原生JS实现滑动轮播图
    H5与企业微信jssdk集成
    img图片不存在显示默认图
  • 原文地址:https://www.cnblogs.com/FriskyPuppy/p/7516647.html
Copyright © 2011-2022 走看看