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.
The first simple solution is to treat each integer as string, sort the strings, then going through the strings in reversed lexicographical order and concatenate them all.
This approach works for some cases like: 99, 87, 34. Result is 998734.
However it doesn't work for [3, 30, 34, 5, 9], since it will generate 9534303 in stead of 9534330. So we need to make sure when we sort the array in a special way that "3" is larger than numbers like "30", "31", "32". Why? Because 330 > 303, 331>313...
How can we archive that? Actually the above comparison results already give us the hint! We can build a comparator, and concatenate the string in different ways and compared them.
Here is the code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static class MyComparator implements Comparator<String>{ | |
public int compare(String s1, String s2){ | |
return (s2+s1).compareTo(s1+s2); | |
} | |
} | |
public String largestNumber(int[] nums) { | |
List<String> strs = new ArrayList<>(); | |
boolean hasNonZero = false; | |
//convert numbers to string | |
for(int n : nums){ | |
if(n>0) | |
hasNonZero = true; | |
strs.add(String.valueOf(n)); | |
} | |
if(!hasNonZero){ | |
return "0"; | |
} | |
Collections.sort(strs, new MyComparator()); | |
StringBuilder sb = new StringBuilder(); | |
for(String s : strs){ | |
sb.append(s); | |
} | |
return sb.toString(); | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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("")); | |
} |
No comments:
Post a Comment