Largest Number

题目:

Given a list of non negative integers, arrange them such that they form the largest number.

分析:

关于取most significant digit的操作,用string来做其实更好一些,他不像least significant digit,可以一直顺次算下去,这个most significant只能做一次,而second most significant就取不出来了。

于是把integer做成string,然后知道char是可以直接用ascii比大小的,就好了。

记住java里面string不接受大于和小于运算,没有overload的方法

解法:

public class Solution {
    /**
     *@param num: A list of non negative integers
     *@return: A string
     */
    public String largestNumber(int[] num) {
        // write your code here
        if(num.length == 0) {
            throw new IllegalArgumentException();
        }
        if (num.length == 1) {
            return Integer.toString(num[0]);
        }

        String[] b = new String[num.length];
        for (int i = 0; i < num.length; i++) {
            b[i] = Integer.toString(num[i]);
        }

        Arrays.sort(b, new Comparator<String>() {
            public int compare(String lhs, String rhs) {
                int i = 0;
                while (i < lhs.length() - 1 && i < rhs.length() - 1 && lhs.charAt(i) == rhs.charAt(i)) {
                    i++;
                }
                return rhs.charAt(i) - lhs.charAt(i);
            }
        });

        Arrays.sort(b, new Comparator<String>() {
            public int compare(String lhs, String rhs) {
                int i = 0;
                while (i < lhs.length() - 1 && i < rhs.length() - 1 && lhs.charAt(i) == rhs.charAt(i) ) {
                    i++;
                }

                int j = i;
                if (i == lhs.length() - 1 ) {
                    while (j < rhs.length() - 1 && lhs.charAt(i) == rhs.charAt(j)) {
                        j++;
                    }
                    return rhs.charAt(j) - lhs.charAt(i);
                }

                if (i == rhs.length() - 1 ) {
                    while (j < lhs.length() - 1 && lhs.charAt(j) == rhs.charAt(i)) {
                        j++;
                    }
                    return rhs.charAt(i) - lhs.charAt(j);
                }

                return rhs.charAt(i) - lhs.charAt(i);
            }
        });

        String res = "";
        for (int i = 0; i < b.length; i++) {
            res += b[i];
        }

        // remove leading "0"s and make sure of "000" appears, return "0"
        int index = 0;
        while (index < res.length() && res.charAt(index) == '0') {
            index++;
        }
        if (index == res.length() ) {
            return "0";
        }
        return res.substring(index);
    }
}

results matching ""

    No results matching ""