[Leetcode] Largest Number
Largest Number
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.
排序法
复杂度
O(nklgnk) 时间 O(N) 空间
思路
这题没法用integer做,得弄成string做,排序
唯一的难点是排序的时候comparator,这么写:
class MyComp implements Comparator {
public int compare(String a, String b) {
String s1 = a + b;
String s2 = b + a;
return s2.compareTo(s1);
}
}
多么的天才!
Credit to: https://discuss.leetcode.com/category/187/largest-number
注意
都是0的情况要注意,特殊判断一下
代码
public class Solution {
class MyComp implements Comparator {
public int compare(String a, String b) {
String s1 = a + b;
String s2 = b + a;
return s2.compareTo(s1);
}
}
public String largestNumber(int[] nums) {
String[] arr = new String[nums.length];
for (int i = 0; i
关键字:leetcode
版权声明
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处。如若内容有涉嫌抄袭侵权/违法违规/事实不符,请点击 举报 进行投诉反馈!