LeetCode179: Maximum number

topic

Given a set of non-negative integers, rearrange their order to form the largest integer.

Example 1:

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

Input: [3,30,34,5,9]
Output: 9534330
Explanation: The output may be very large, so you need to return a string instead of an integer.

Passed 37,345 Submitted 101,676

Source: LeetCode
Link: https://leetcode-cn.com/problems/largest-number
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Method: Convert it into a string and sort it in descending order of the dictionary.

class Solution {
    
    
    public String largestNumber(int[] nums) {
    
    
        if(nums==null||nums.length==0)
            return "";
        String[]str = new String[nums.length];
        for(int i=0;i<nums.length;i++){
    
    
            str[i] = String.valueOf(nums[i]);
        }
        Arrays.sort(str,new Comparator<String>(){
    
    
            @Override
            public int compare(String s1,String s2){
    
    
               
                return (s2+s1).compareTo(s1+s2);
                /*
                假设(不是一般性),某一对整数 a 和 b ,我们的比较结果是 a 应该在 b 前面,这意味着a+b>b+a;
                如果排序结果是错的,说明存在一个 c, b 在 c 前面且 c 在 aa 的前面。这产生了矛盾,因为 a+ b> b+a和 b+c>c+b 意味着 a+c>c+a。
                换言之,我们的自定义比较方法保证了传递性,所以这样子排序是对的。
				一旦数组排好了序,最“重要”的数字会在最前面。
				有一个需要注意的情况是如果数组只包含 0 ,我们直接返回结果 00 即可。否则,我们用排好序的数组形成一个字符串并返回。
                */
            }
        });
        StringBuilder sb = new StringBuilder();
        for(String as:str){
    
    
            sb.append(as);
        }
        String result = sb.toString();
        if(result.charAt(0)=='0')
            result="0";
        return result;

    }
}

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_44861675/article/details/107834517