[LintCode]Reorder array to construct the minimum number

http://www.lintcode.com/en/problem/reorder-array-to-construct-the-minimum-number/#

給一個數組,按照最終拼成的最小數字排序




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.




直接轉成string,然後兩個數拼一下,比較誰在前更小就行了。另外注意前綴0和全爲零的情況。

public class Solution {
    public String minNumber(int[] nums) {
        // Write your code here
        String[] arr = new String[nums.length];
        for (int i = 0; i < nums.length; i++) {
            arr[i] = nums[i] + "";
        }
        Arrays.sort(arr, new Comparator<String>() {
            public int compare(String s1, String s2) {
                return (s1 + s2).compareTo(s2 + s1);
            }
        });
        StringBuilder sb = new StringBuilder();
        for (String s : arr) {
            if (sb.length() == 0 && s.equals("0")) {
                continue;
            }
            sb.append(s);
        }
        return sb.length() == 0 ? "0" : sb.toString();
    }
}


發佈了363 篇原創文章 · 獲贊 1 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章