Catalogue
- Directory
- Topic
- Ideas
- AC Code
Topics
Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 5, 9], and the largest formed number is 9534330.
Note:the result May is very large, so you need to return a string instead of an integer.
Ideas
The idea is clear: convert the int num array to a string num array, and then sort it. The rules for sorting are as follows:
For example strings str1 and str2, stitching strings CMP1 = str1 + str2,cmp2 = str2 + str1. Sort by dictionary, if CMP1 > cmp2, then str1 > str2. Conversely, then str1 < str2.
Note: You can use the comparator interface provided by Java, and then implement the dictionary in reverse order.
Cpmparator interface use can refer to my blog: comparator and comparable use the difference.
AC Code
The AC code is as follows:
Public class solution { Public StaticStringLargestnumber(int[] num) {StringBuilder res =NewStringBuilder (); string[] Numarrays =NewString[num.length];intZeronum =0; for(inti =0; i < num.length; i + +) {if(Num[i] = =0) {zeronum + +; } Numarrays[i] = integer.tostring (Num[i]); }if(Zeronum = = num.length) {return "0"; } arrays.sort (Numarrays,NewNumcomparator ()); for(String s:numarrays) {Res.append (s); }returnRes.tostring (); }Private Static class numcomparator implements Comparator<String> { @Override Public int Compare(String str1, String str2) {String CMP1 = str1 + str2; String CMP2 = str2 + str1;returnCmp1.compareto (CMP2) *-1; } }}
[Leetcode] Largest number, problem solving report