zoukankan      html  css  js  c++  java
  • 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.

    class Solution {
        private class LargerNumberComparator implements Comparator<String> {
            @Override
            public int compare(String a, String b) {
                String order1 = a + b;
                String order2 = b + a;
               return order2.compareTo(order1);
            }
        }
    
        public 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 LargerNumberComparator());
    
            // 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;
        }
    }

    重写comparator interface 里面的compare方法,然后使用method Arrays.sort(array[], new Comparator<String>());

    a+b比b+a是升序,b+a比a+b是降序排列。

    While it might be tempting to simply sort the numbers in descending order, this causes problems for sets of numbers with the same leading digit.

    For example, sorting the problem example in descending order would produce the number 95343039534303,

    while the correct answer can be achieved by transposing the 33 and the 3030. Therefore, for each pairwise comparison during the sort,

    we compare the numbers achieved by concatenating the pair in both orders. We can prove that this sorts into the proper order as follows:

    就是说"3" "30"的时候,会判断出30比3大,所以30在前面生成303,我们想要的其实是330.

    所以用3+30和30+3比较,结果自然是330比较大。

    再说一下compareTo方法,比如3和1,比较结果就是2,4和1,结果是3,相反就加负号。

  • 相关阅读:
    代码注释技术
    疑难杂症错误解决方法大全
    MD5 加密
    ADO.NET DataReader和DataAdapter的区别
    HTTP协议详解
    web开发常用样式
    Stream 和 byte[] 之间的转换
    Sql 函数大全 (更新中...由难到简
    Web C# 导出Excel 方法总结
    VC++ MFC 如何实现在编辑框中输出具有换行功能的文段 01
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10687369.html
Copyright © 2011-2022 走看看