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.

    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.

    含义:给定多个非负数,将他们排列成一个最大数,用string返回

     1     public String largestNumber(int[] nums) {
     2         if(nums == null || nums.length == 0)
     3             return "";
     4 
     5         // Convert int array to String array, so we can sort later on
     6         String[] s_num = new String[nums.length];
     7         for(int i = 0; i < nums.length; i++)
     8             s_num[i] = String.valueOf(nums[i]);
     9 
    10         // Comparator to decide which string should come first in concatenation
    11         Comparator<String> comp = new Comparator<String>(){
    12             @Override
    13             public int compare(String str1, String str2){
    14                 String s1 = str1 + str2;
    15                 String s2 = str2 + str1;
    16                 return s2.compareTo(s1); // reverse order here, so we can do append() later
    17             }
    18         };
    19 
    20         Arrays.sort(s_num, comp);//由顶到底,前一个元素加后一个元素的值,大于后一个元素加前一个元素的值
    21         // An extreme edge case by lc, say you have only a bunch of 0 in your int array
    22         if(s_num[0].charAt(0) == '0')
    23             return "0";
    24 
    25         StringBuilder sb = new StringBuilder();
    26         for(String s: s_num)
    27             sb.append(s);
    28 
    29         return sb.toString();        
    30     }
  • 相关阅读:
    do...while(0)的妙用
    2013-07-23工作记录
    2013-07-22工作记录
    完全零基础入门——第二天
    【转】学习Flex ActionScript 3.0 强烈推荐电子书
    完全零基础入门——第一天
    【转】待整理
    【luogu P7599】雨林跳跃
    【ybt金牌导航5-4-4】【luogu P4842】城市旅行
    【ybt金牌导航5-4-3】【luogu P2387】魔法森林
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7731612.html
Copyright © 2011-2022 走看看