179. Largest Number

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

Example 1:

Input: [10,2]
Output: "210"

Example 2:

Input: [3,30,34,5,9]
Output: "9534330"

难度:medium

题目:给定非负整数数组,重组其序使其形成最大值。

思路:定制排序算法的比较策略,nums[i]拼接nums[j] 与 nums[j]拼接nums[i] 相比。

Runtime: 51 ms, faster than 26.58% of Java online submissions for Largest Number.
Memory Usage: 35.7 MB, less than 100.00% of Java online submissions for Largest Number.

class Solution {
    public String largestNumber(int[] nums) {
        if (null == nums) {
            return "0";
        }
        int n = nums.length;
        String[] ss = new String[n];
        for (int i = 0; i < n; i++) {
            ss[i] = String.valueOf(nums[i]);
        }
        Arrays.sort(ss, (s1, s2) -> {
            String s1s2 = s1 + s2;
            String s2s1 = s2 + s1;
            return s2s1.compareTo(s1s2);
        });

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            sb.append(ss[i]);
        }
        String result = new String(sb);
        
        return '0' == result.charAt(0) ? "0" : result;
    }
}
    原文作者:linm
    原文地址: https://segmentfault.com/a/1190000018147827
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞