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.

    【分析】

    1.设置一个比较器Comparator,比较两个String按不同方式拼接后的数字的大小(如String a和b,parseLong(a+b)和parseLong(b+a))

    2.考虑int的范围,当两个数字拼接后可能会超出int的范围,采用Long来拼接两个int

    【算法实现】

    public class Solution {
        public String largestNumber(int[] nums) {
            int len = nums.length;
            if(len<1)
                return "";
            String[] str = new String[len];
            for(int i=0; i<len; i++) {
                str[i] = String.valueOf(nums[i]);
            } 
            Arrays.sort(str,new Cmp());
            
            StringBuffer res = new StringBuffer();
            for(int i=0; i<len; i++) {
                res.append(str[i]);
            }
            
            String r = res.toString();
            int i = 0;
            while(i<len && r.charAt(i)=='0') {
                i++;
            }
            if(i==len)
                return "0";
            
            return res.toString();
        }
        
        class Cmp implements Comparator<String> {
            public int compare(String s1, String s2) {
                String a = s1.concat(s2);
                String b = s2.concat(s1);
                int res;
                if((Long.parseLong(b)-Long.parseLong(a))>0) {
                    res = 1;
                }else if((Long.parseLong(b)-Long.parseLong(a))<0) {
                    res = -1;
                }else {
                    res = 0;
                }
                return res;
            }
        }
    }
  • 相关阅读:
    02-30 线性可分支持向量机
    02-28 scikit-learn库之线朴素贝叶斯
    02-27 朴素贝叶斯
    02-26 决策树(鸢尾花分类)
    047 选项模式
    第二节:师傅延伸的一些方法(复习_总结)
    第一节:登录流程
    第一节:对应拼音编码查询(后续更新)
    前端对象
    Form表单
  • 原文地址:https://www.cnblogs.com/hwu2014/p/4512744.html
Copyright © 2011-2022 走看看