【剣指Offer面接問題】9度OJ 1504:配列を最小にする数

4694 ワード

タイトルリンクアドレス:http://ac.jobdu.com/problem.php?pid=1504
タイトル1504:配列を最小にする
时间制限:1秒メモリ制限:128メガ特殊判题:No提出:1696解决:533题描述:正の整数配列を入力し、配列内のすべての数字をつなぎ合わせて1つの数に并べ、つなぎ合わせることができるすべての数字の中で最小の1つを印刷します.例えば配列{3,32321}を入力すると、この3つの数字が並べられる最小数字は321323となる.入力:入力には複数のテストサンプルが含まれる場合があります.各テストケースについて、入力された第1の動作の整数m(1<=m<=100)は、入力された正の整数の個数を表す.入力された2行目はm個の正の整数を含み、各正の整数は1000000を超えない.出力:各テストケースに対応して、m個の数字が並べられる最小数字を出力します.サンプル入力:3 23 13 6 2 23456サンプル出力:13234556
カスタム比較関数を書く
  • 数値mおよびnについては、まず文字列
  • に変換する
  • その組合せmnとnmの大きさを比較
  • 最終用
  • sortソート
  • /********************************* 【  Offer   】   OJ1504:          Author:    Date:2015  Email:[email protected] **********************************/
    #include <stdio.h>
    #include <stdlib.h> 
    #include <string>
    #include <cstring>
    #include <math.h>
    #include <stack>
    #include <vector>
    #include <queue> 
    #include <iostream>
    #include<algorithm>
    #include <map>
    #include <queue>
    using namespace std;
    char strs[100][10];
    int mycompare(const void *str1,const void *str2)
    {
        static char s1[20];
        static char s2[20];
        char *string1 = (char *)str1;
        char *string2 = (char *)str2;
        sprintf(s1,"%s%s",string1,string2);
        sprintf(s2,"%s%s",string2,string1);
        return strcmp(s1,s2);
    }
    void PrintMinNum(int *nums,int len)
    {
        if(nums==NULL || len<1)
            return;
    
        int i;
        for(i=0;i<len;i++)
            sprintf(strs[i],"%d",nums[i]);
        qsort(strs,len,10*sizeof(char),mycompare);
    
        for(i=0;i<len;i++)
            printf("%s",strs[i]);
        printf("
    "
    ); } int main() { int nums[100]; int m; while(scanf("%d",&m) != EOF) { int i; for(i=0;i<m;i++) scanf("%d",nums+i); PrintMinNum(nums,m); } return 0; } /************************************************************** Problem: 1504 Language: C++ Result: Accepted Time:240 ms Memory:1520 kb ****************************************************************/