Leetcode Largest Number

本文介绍了一种算法,用于将非负整数数组重新排列形成最大的可能数值。通过自定义比较器实现数组元素的特殊排序,确保组合成的目标数字最大化。

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

Problem

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

For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.

Note: The result may be very large, so you need to return a string instead of an integer.




Idea: After observing the array and the 

returned result, here we need to think 

for example, when given num1 = 5

num2 = 34, why we put num1 before num2. 

 The answer is simple, that is because

 num1 + num2 (534)  >  num2 + num1 (345). 

  Therefore, we need to first sort the

 array such that each adjacent two 

numbers (indicate them by n1 and n2,

  and assume that n1 is before n2 in

 the sorted array) satisfy the rule 

that  n1 + n2 > n2 + n1.  

So we need to first rewrite the Comparator.



Code:

public class Solution {
	class MyComparator implements Comparator<String> {
		public int compare (String s1, String s2) {
			String str1 = s1 + s2;
			String str2 = s2 + s2;
			return str2.compareTo(str1);
		}
	}
	public String largestNumber(int[] num) {
		String[] strArray = new String[num.length];
		for (int i = 0; i < num.length; i++) {
			strArray[i] = String.valueOf(num[i]);
		}
		Comparator<String> comparator = new MyComparator();
		Arrays.sort(strArray, comparator);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < num.length; i++) {
			sb.append(strArray[i]);
		} 
		return sb.charAt(0) == '0' ? "0" : sb.toString();
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值