Leetcode 179: largest number

Leetcode 179: largest number

https://leetcode.com/problems/largest-number/

1, what is the largest number looks like?

2, how to make the arrangement in order to make the number large?
example:
1,2,5,34,36 –> 1243436, 5363421

3, the first idea is do the comparation carefully
1) find the largest highest digit in all numbers (may not find the final largest number) : 9123, 89, 77,
2) if there is two same largest digits, compare them and find the second largest digit in the two numbers
3) may use string comparation
String.sort()
Then I come up code like this:

public static String largestNumber(int[] nums) {
    String[] a = new String[nums.length];
    for (int i = 0; i < nums.length; ++i) {
        a[i] = nums[i] + "";
    }
    Arrays.sort(a, Collections.reverseOrder());
    String res = "";
    for (String num : a) {
        res += num;
    }
    return res;
}

4, when I finish the code, I found my solution cannot pass the test case: [121, 12]
1) there two possible arrangement: 12112, 12121
2) if we chose string comparation, the largest number should be 121, and the smaller would be 12
3) that means, if two numbers first few digits are same,
for example: 886,88,
we need to check other numbers in the nums[],
if there is 7x.. we need to chose 887x.. instead of 886..

5, So the custom comparation has some problems:
it need to compare the sum of the different arrangement of the two numbers:
for example: 121 and 12
we need to compare 12112 and 12121
Another exmaple: 98 and 999
we need to compare 98999 and 99998

6, the final code would be a little change:

public String largestNumber(int[] nums) {
    String[] a = new String[nums.length];
    for (int i = 0; i < nums.length; ++i) {
        a[i] = nums[i] + "";
    }
    Arrays.sort(a,(str1,str2) -> (str2 + str1).compareTo(str1 + str2));
    if(a[0].equals("0")) return "0";
    String res = "";
    for (String num : a) {
        res += num;
    }
    return res;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值