zoukankan      html  css  js  c++  java
  • 179. Largest Number 用数组中的元素凑一个最大数字

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

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

     

    Example 1:

    Input: nums = [10,2]
    Output: "210"
    

    Example 2:

    Input: nums = [3,30,34,5,9]
    Output: "9534330"
    

    Example 3:

    Input: nums = [1]
    Output: "1"
    

    Example 4:

    Input: nums = [10]
    Output: "10"

    思路:首先排序,但也30 > 9 这样的也不对啊
    正解:利用了s2.compareTo(s1)这个自带的函数,按lexi排序

    Comparator接口,用法上和抽象类一样吧。就按类来写就行了

    class Solution {
        public String largestNumber(int[] nums) {
            //cc
            if (nums == null || nums.length == 0)
                return "";        
            
            //转成string[]
            String[] strs = new String[nums.length];
            for (int i = 0; i < strs.length; i++) {
                strs[i] = String.valueOf(nums[i]);
            }
            
            //写个排序
            Comparator<String> comparator = new Comparator<String>(){            
                @Override
                public int compare(String s1, String s2) {
                    String str1 = s1 + s2;
                    String str2 = s2 + s1;                
                    return str2.compareTo(str1);
                }
            };
            
            //排序
            Arrays.sort(strs, comparator);
            
            // An extreme edge case by lc, say you have only a bunch of 0 in your int array
            if(strs[0].charAt(0) == '0')
                return "0";
            
            //粘贴一下
            StringBuilder sb = new StringBuilder();
            for (String str : strs) {
                sb.append(str);
            }
            
            return sb.toString();
        }
    }
    View Code
     
  • 相关阅读:
    SQL函数——CASE
    初始Oracle
    ASP.NET中JQuery+AJAX调用后台
    性能优化——SQL语句(续)
    性能优化——SQL语句
    今日开讲—— easyui-combobox动态赋值
    SSH 项目建立过程
    Util
    前端 s 标签获取值
    日期选择文本框
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13845181.html
Copyright © 2011-2022 走看看