[Leetcode] Largest number, problem solving report

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.