leet179:最大数

标签: leet数组

在这里插入图片描述

private static class LargerN1umberComparator implements Comparator<String> {
    @Override
    public int compare(String a, String b) {
        String order1 = a + b;
        String order2 = b + a;
        return order2.compareTo(order1);
    }
}

public static String largestNumber(int[] nums) {
    // Get input integers as strings.
    String[] asStrs = new String[nums.length];
    for (int i = 0; i < nums.length; i++) {
        asStrs[i] = String.valueOf(nums[i]);
    }

    // Sort strings according to custom comparator.
    Arrays.sort(asStrs, new LargerN1umberComparator());

    // If, after being sorted, the largest number is `0`, the entire number
    // is zero.
    if (asStrs[0].equals("0")) {
        return "0";
    }

    // Build largest number from sorted array.
    String largestNumberStr = new String();
    for (String numAsStr : asStrs) {
        largestNumberStr += numAsStr;
    }

    return largestNumberStr;
}

也可以使用JDK8提供的stream
不过时间复杂度较低

public String larges1tNumber(int[] nums) {
     StringBuilder res;
    res = new StringBuilder();
    Arrays.stream(nums).boxed().map(x -> x.toString()).sorted((x, y) -> (y + x).compareTo(x + y)).forEach(x -> res.append(x));
    return res.charAt(0) == '0' ? "0" : res.toString();
}
版权声明:本文为qq_38304320原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_38304320/article/details/103921928