• 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;
            }
        }
    }
  • 相关阅读:
    linux开机自动挂载NTFS-WINDOWS分区
    s3c6410学习笔记-烧写uboot+构建文件系统
    C++静态库与动态库(简介)
    linux下gmplayer安装(亲测OK!)
    得到IP包的数据意义(简单实现例子)
    IP校验和
    汇编三个数选最大
    单链表练习
    汇编写下strcpy
    排序好后写入文件
  • 原文地址:https://www.cnblogs.com/hwu2014/p/4512744.html
Copyright © 2020-2023  润新知