zoukankan      html  css  js  c++  java
  • [leed code 179] Largest Number

    1 题目

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

    For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.

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

    2 方法

    刚开始就误入歧途,准备按字符来比较,结果逻辑各种复杂,网上查了查,结果发现直接比较两个连起来的字符串要简单的多。比如字符串a和字符串b,比较ab和ba的大小就搞定了。

    3 代码

         public String largestNumber(int[] num){
                String[] strArray = new String[num.length];
                for (int i = 0; i < num.length; i++) {
                    strArray[i] = Integer.toString(num[i]);
                }
                strArray = this.anotherSort(strArray);//(strArray);
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < strArray.length; i++) {
                    sb.append(strArray[i]);
                }
                String out = sb.toString();
                if(out.charAt(0) == '0') return "0";
                return out;
            }
        public static String[] anotherSort(String[] strSort) {
            String temper = "";
            for (int i = 0; i < strSort.length; i++) {
                for (int j = i + 1; j < strSort.length; j++) {
                    String add1 = strSort[i] + strSort[j];
                    String add2 = strSort[j] + strSort[i];
                    int out = add1.compareTo(add2);
                    if (out < 0) {
                        temper = strSort[i];
                        strSort[i] = strSort[j];
                        strSort[j] = temper;
                    }
                }
            }
            return strSort;
        }    
  • 相关阅读:
    python IDE比较与推荐
    一个平庸程序员的想法
    [转载]Malcolm的新书:Outliers
    程序员的编辑器——VIM
    Blender网络资源
    普通人的编辑利器——Vim
    易学易用的Windows PowerShell
    分区表的修复(转)
    云南电信DNS服务器地址
    滇南本草(上)
  • 原文地址:https://www.cnblogs.com/lingtingvfengsheng/p/4280636.html
Copyright © 2011-2022 走看看