*[Lintcode]Largest Number 最大数

本文介绍了一种算法,用于将一组非负整数重新排列形成最大的可能数值。通过自定义比较器进行排序,确保组合成的字符串形式能表示最大的整数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a list of non negative integers, arrange them such that they form the largest number.


Example

Given [1, 20, 23, 4, 8], the largest formed number is 8423201.

如果不想重写排序算法的话,使用Arrays.sort需要注意,必须将int数组改为对象类型,并且重写comparato
public class Solution {
    /**
     *@param num: A list of non negative integers
     *@return: A string
     */
    public String largestNumber(int[] num) {
        if(num.length == 0) return "";

        String[] strList = new String[num.length];
        
        for(int i = 0; i < num.length; i++) strList[i] = "" + num[i];
        
        Arrays.sort(strList, new comparatorI());

        int NonZero = 0;
        while(NonZero < strList.length && "0".equals(strList[NonZero]))
            NonZero++;

        StringBuilder sb = new StringBuilder();
        for(int i = NonZero; i < strList.length; i++){
            sb.append(strList[i]);
        }
        return sb.length() == 0 ? "0" : sb.toString();
    }
    
    class comparatorI implements Comparator<String> {
        public int compare(String s1, String s2) {
            return (s2 + s1).compareTo(s1 + s2);  
        }
    }
}

r。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值