java非负数,在Java中,如何找到给定非负数数组的最大可能数

Problem Statement:

I have an array of non-negative numbers in form of String in Java, I want to arrange the integers to form the largest possible number.

Example: Given below input:

String[] numbers = {"15", "9", "62", "34"};

The arrangement "9623415" gives the largest number.

Note: I understand we can sort all numbers in descending order, but simply sorting doesn’t work. For example, 15 is larger than 9 in natural order but "9" comes before "15" in the solution. What's the best way to implement a custom comparator in this case?

Any help would be appreciated.

解决方案

the method public int compareTo(String anotherString) of a String is what you need which gives you the order of the String lexicographically .

Update1:

What is lexicographic ordering.

Frome Java Doc:

This is the definition of lexicographic ordering. If two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both. If they have different characters at one or more index positions, let k be the smallest such index; then the string whose character at position k has the smaller value, as determined by using the < operator, lexicographically precedes the other string. In this case, compareTo returns the difference of the two character values at position k in the two string -- that is, the value:

this.charAt(k)-anotherString.charAt(k)

If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings -- that is, the value:

this.length()-anotherString.length()

So String 9will appear ahead of String 15 in a lexicographic ordering, since they have different characters at index 0, and char 9 is larger than char 1. If you read about lexicographic ordering carefully you will find that that order is just what the OP needs!

Update2: Why lexicographic ordering is the key for this question

The lexicographic order of the Strings in the question is like this:

"9", "62", "34","15"

So after you get this order, the question should be trival: just iterate the ordered sequence and you get the answer.

Update 3: How to handle special case like: "9"&"90", since we need "990" instead of "909"

In this case the lexicographic ordering will fail. But it is easy to figure out a fix:

Instead of str1.compareTo(str2), we can use (str2+str1).compareTo(str1+str2). The key here is to ensure these two strings have at least a bit of different digit, so we don't get the order by comparing there lengths.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值