Reorder array to construct the minimum number

Source: Internet
Author: User

Construct minimum number by reordering a given non-negative integer array. Arrange them such that they form the minimum number.

Notice

The result is very large, so you need to return a string instead of an integer.

Has you met this question in a real interview? Example

Given [3, 32, 321] , there is 6 possible numbers can be constructed by reordering the array:

3+32+321=3323213+321+32=33213232+3+321=32332132+321+3=323213321+3+32=321332321+32+3=321323

So after reordering, the minimum number is 321323 , and return it.

Analysis:

We need to sort the arrays here, so how do we compare the sizes? For numbers A and B, if the number of AB together is less than the number of BA composition, we think A<b, and vice versa.

1  Public StaticString Minnumber (int[] nums) {2     if(Nums = =NULL|| Nums.length = =0)3         return "";4 5string[] STRs =NewString[nums.length];6      for(inti =0; i < nums.length; i++) {7Strs[i] =string.valueof (Nums[i]);8     }9 TenArrays.sort (STRs,NewComparator<string>() { One          Public intCompare (String str1, String str2) { A             return(str1 + str2). CompareTo (str2 +str1); -         } -     }); the  -StringBuilder SB =NewStringBuilder (); -      for(String str:strs) { - sb.append (str); +     } -      for(inti =0; I < sb.length (); i++) { +         if(Sb.charat (i)! ='0') { A             returnsb.substring (i); at         } -     } -     return "0"; -}

Reorder array to construct the minimum number

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.