[leetcode]179. Largest Number最大数

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

Input: [10,2]
Output: "210"
Input: [3,30,34,5,9]
Output: "9534330"

题意:

给定一堆数字,将它们排列顺序,使其连一块儿能形成最大的数。

思路:

先转化成一个字符串数组

然后把这个数组按特定规则排个序(熟练使用字符串的compareTo方法)

最后建一个StringBuilder

将排好序的字符串按顺序加到StringBuilder后面(注意字符串开头可能为0的极端情况)

最后将StringBuilder转成String输出

代码:

 1 class Solution {
 2     public String largestNumber(int[] a) {
 3         
 4         // int[] --> String[]
 5         String[] array = new String[a.length];
 6         for(int i = 0; i< a.length; i++){
 7             array[i] = a[i] +"";
 8         }
 9         
10         // sort string
11         Arrays.sort(array, (sA, sB)->(sB + sA).compareTo(sA + sB));
12         
13         // string[] -> result
14         StringBuilder sb = new StringBuilder();
15         for (String s : array) {
16              sb.append(s);
17         }
18 
19         return sb.charAt(0) == '0' ? "0" : sb.toString(); 
20     }
21 }

猜你喜欢

转载自www.cnblogs.com/liuliu5151/p/9158199.html