LeetCode - Largest Number

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

For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.

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

 

各种corner case都要考虑,比如

  • 343和34,谁放到前面?34334<34343,所以34放在前面。
  • 344和34,谁放到前面?34434>34344,所以344放在前面。
  • 所有数都为零的情况,要把前面的零去掉,只留下一个。
  • 可以考虑用PriorityQueue对数据进行排序,或者直接创建数组排序。

 

Solution:

public String largestNumber(int[] num) {
    if(num==null || num.length==0) return "0";
    Queue<String> q = new PriorityQueue<String>(num.length, new Comparator<String>() {
        public int compare(String a, String b) {
            String s1 = a+b;
            String s2 = b+a;
            return s2.compareTo(s1);
        }
    });
    for(int e:num) {
        q.offer(""+e);
    }
    StringBuilder sb = new StringBuilder();
    while(!q.isEmpty()) {
        sb.append(q.poll());
    }
    while(sb.charAt(0)=='0' && sb.length()>1) {
        sb.deleteCharAt(0);
    }
    return sb.toString();
}

 

你可能感兴趣的:(LeetCode)