## Friday, February 12, 2016

### LeetCode - Largest Number (Java)

LeetCode – Largest Number (Java)
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.)

This problem can be solve by simply sorting strings, not sorting integer. Define a comparator to compare strings by concat() right-to-left or left-to-right.
``` public String largestNumber(int[] nums) { String[] strs = new String[nums.length]; for(int i=0; i<nums.length; i++){ strs[i] = String.valueOf(nums[i]); }   Arrays.sort(strs, new Comparator<String>(){ public int compare(String s1, String s2){ String leftRight = s1+s2; String rightLeft = s2+s1; return -leftRight.compareTo(rightLeft);   } });   StringBuilder sb = new StringBuilder(); for(String s: strs){ sb.append(s); }   while(sb.charAt(0)=='0' && sb.length()>1){ sb.deleteCharAt(0); }   return sb.toString(); } ```
http://www.cnblogs.com/yuzhangcmu/p/4235285.html
``` 2     public String largestNumber(int[] num) {
3         // 1045
4         // 1111 begin.
5         if (num == null) {
6             return null;
7         }
8
9         ArrayList<Integer> list = new ArrayList<Integer>();
10         for (int n1: num) {
12         }
13
14         Collections.sort(list, new Comparator<Integer>(){
15             public int compare(Integer o1, Integer o2) {
16                 String s1 = "" + o1 + o2;
17                 String s2 = "" + o2 + o1;
18
19                 return s2.compareTo(s1);
20             }
21         });
22
23         StringBuilder sb = new StringBuilder();
24         for (int n: list) {
25             sb.append(n);
26         }
27
28         if (sb.charAt(0) == '0') {
29             return "0";
30         }
31
32         return sb.toString();
33     }
34 }```
http://blueocean-penn.blogspot.com/2016/01/largest-number-leetcode.html
If we use Java8 stream API, without worrying about the all 0s case, this solution becomes a one-liner!!!
public static String largestNumber(int[] nums) {
return Arrays.stream(nums)
.mapToObj(p->String.valueOf(p))
.sorted((s1, s2)->(s2+s1).compareTo(s1+s2))
.collect(Collectors.joining(""));
}