Wednesday, July 8, 2015

Largest Number

Given a list of non negative integers, arrange them such that they form the largest number.
Have you met this question in a real interview? 
Yes
Example
Given [1, 20, 23, 4, 8], the largest formed number is 8423201.

Note
The result may be very large, so you need to return a string instead of an integer.
public class Solution {
    /**
     *@param num: A list of non negative integers
     *@return: A string
     */
    public String largestNumber(int[] nums) {
        // write your code here
        if(nums == null || nums.length == 0) return null;
        String[] numString = new String[nums.length];
        for(int i = 0; i < nums.length; i++){
            numString[i] = String.valueOf(nums[i]);
        }
       
        Arrays.sort(numString, new Comparator<String>(){
            public int compare(String a, String b){
                String lr = a+b;
                String rl = b+a;
                return rl.compareTo(lr);
            }
        });
        StringBuffer buffer = new StringBuffer();
        for(String s : numString){
            buffer.append(s);
        }
        if(buffer.charAt(0) == '0') return "0";
        return buffer.toString();
    }
}

No comments:

Post a Comment