1. 程式人生 > 實用技巧 >劍指Offer_#45_把陣列排成最小的數

劍指Offer_#45_把陣列排成最小的數

劍指Offer_#45_把陣列排成最小的數

劍指offer

Contents

題目

輸入一個非負整數陣列,把數組裡所有數字拼接起來排成一個數,列印能拼接出的所有數字中最小的一個。

示例 1:

輸入: [10,2]
輸出: "102"

示例2:

輸入: [3,30,34,5,9]
輸出: "3033459"

提示:

0 < nums.length <= 100

說明:
輸出結果可能非常大,所以你需要返回一個字串而不是整數
拼接起來的數字可能會有前導 0,最後結果不需要去掉前導 0

思路分析

需要定義一種特殊的比較規則,根據這種比較規則對數字進行排序,然後將排序後的數字重新拼接起來,就得到最小數字。
比較規則:


兩個數字x,y按照字串拼接的形式,可以拼成x+y,y+x,比較這兩個拼接數字的大小,如果x+y > y+x,判斷為x>y,即a應該靠後;反之同理。
如圖

解答

class Solution {
    public String minNumber(int[] nums) {
        //將int陣列轉換為String陣列,便於進行比較
        String[] strArray = new String[nums.length];
        for(int i = 0;i <= nums.length - 1;i++){
            strArray[i] = String.valueOf(nums[i]);
        }
        //利用String物件的compareTo方法,指定sort函式當中的比較規則
Arrays.sort(strArray, (str1, str2) -> (str1 + str2).compareTo(str2 + str1)); //將排序好的陣列組合成字串 StringBuilder res = new StringBuilder(); for(String str:strArray){ res.append(str); } return res.toString(); } }

public static <T> void sort(T[] a,Comparator<? super T> c)


這是Arrays.sort()方法的一種形式。
此函式可以實現自定義的比較器,來比較任意型別T組成的陣列。
以下是文件內容:

Sorts the specified array of objects according to the order induced by the specified comparator. All elements in the array must be mutually comparable by the specified comparator (that is, c.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the array).
Type Parameters:
T - the class of the objects to be sorted
Parameters:
a - the array to be sorted
c - the comparator to determine the order of the array. A null value indicates that the elements' natural ordering should be used.

String型別的CompareTo函式
以下是CompareTo()函式的文件,說明上述程式碼的正確性,對於表示數字的字串,直接用compareTo()函式即可比較出字串表示的數字的大小關係。