1. 程式人生 > >Reorder array to construct the minimum number 解題報告

Reorder array to construct the minimum number 解題報告

Reorder array to construct the minimum number

Description

Construct minimum number by reordering a given non-negative integer array. Arrange them such that they form the minimum number.

Notice

The result may be very large, so you need to return a string instead of an integer.

Example

Given [3, 32, 321], there are 6 possible numbers can be constructed by reordering the array:

3+32+321=332321
3+321+32=332132
32+3+321=323321
32+321+3=323213
321+3+32=321332
321+32+3=321323

So after reordering, the minimum number is 321323, and return it.

Challenge

Do it in O(nlogn) time complexity.

實現思路

這道題關鍵在於字串兩兩之間的大小比較以及排序演算法。
這裡排序演算法用Java底層用歸併實現的Arrays.sort,能將排序的時間複雜度控制在O(n*lnon)。
對於字串的兩兩比較,按照我們這道題的思路,我們需要比較的是兩兩字串s1,s2拼接是s1拼s2還是s2拼s1大,根據這句話,我們就可以直接通過比較s1+s2和s2+s1的字元序大小來得到我們的結果。
因為是要求最小的數,所以可能0會出現在最後拼接成的字串最前面,我們需要把前導0去掉。

/**public class Solution {
    /**
     * @param nums n non-negative integer array
     * @return
a string */
public String minNumber(int[] nums) { int length = nums.length; String[] numstrs = new String[length]; for (int i = 0; i < length; i++) { numstrs[i] = String.valueOf(nums[i]); } Arrays.sort(numstrs,new Comparator<String>() { @Override public int compare(String o1, String o2) { return (o1+o2).compareTo(o2+o1); } }); StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; i++) { sb.append(numstrs[i]); } while(sb.length() > 1){ if(sb.charAt(0) == '0'){ sb.deleteCharAt(0); }else{ break; } } return sb.toString(); } }