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.)
http://www.cnblogs.com/yuzhangcmu/p/4235285.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(""));
}
Read full article from 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.
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) { 11 list.add(n1); 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(""));
}
Read full article from LeetCode – Largest Number (Java)