文章 224
评论 6
浏览 200766
String - 179. Largest Number

String - 179. Largest Number

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"

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

思路:

贪心的思想,比较相邻两个字符串拼接结果,比较大小。

代码:

java:

class Solution {

    public String largestNumber(int[] nums) {

        if (nums == null || nums.length == 0) return "";
        
        int len = nums.length;
        
        String [] strs = new String[len];
        for (int i = 0; i < len; i++) {
            strs[i] = String.valueOf(nums[i]);
        }
        
        Comparator<String> comp = new Comparator<String>(){
            @Override
            public int compare(String str1, String str2) {
                String s1 = str1 +str2;
                String s2 = str2 +str1;
                return s2.compareTo(s1);
            }
        };
        
        Arrays.sort(strs, comp);
        if(strs[0].charAt(0) == '0') return "0";
        
        StringBuilder sb = new StringBuilder();
        for (String s : strs) {
            sb.append(s);
        }
        
        return sb.toString();
    }
}

标题:String - 179. Largest Number
作者:michael
地址:https://www.bitbo-liuyang.com/articles/2019/07/01/1561990213516.html

Nothing just happens, it's all part of a plan.

取消