• [LeetCode] 179. Largest Number Java


    题目:

    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.

    题意及分析:给出一个数组,求用数组里的元素能组成的最大数。我们可以随便去两个元素来看:s1=782,s2=9,那么s1+s2=7829,s2+s1=9782,我们可以得到s2在s1前面得到的数一定比s1在s2前面打,所以,我们可以用s1+s2与s2+s1的大小判断哪个元素在前面。最后用一个stringbuilder,这样就不用重复创建新string对象了

    代码:

    public class Solution {
        public String largestNumber(int[] nums) {
            if(nums == null || nums.length == 0)
    		    return "";
            String[] strings = new String[nums.length];
            
            for(int i=0;i<nums.length;i++){
            	strings[i]=nums[i]+"";
            }
            
            Arrays.sort(strings,new Comparator<String>() {
    
    			@Override
    			public int compare(String o1, String o2) {
    				// TODO Auto-generated method stub
    				String s1=o1+o2;
    				String s2=o2+o1;
    				return s2.compareTo(s1);
    			}
            	
    		});
            if (strings[0].charAt(0) == '0') return "0";  //最前面的数为0,说明数组全部为0,这时候返回0
            StringBuilder reStringBuilder=new StringBuilder();
            for(int i=0;i<strings.length;i++){
            	reStringBuilder.append(strings[i]);
            }
            //System.out.println(reStringBuilder.toString());
            return reStringBuilder.toString();
        }
    }
    

      

  • 相关阅读:
    Linux 文件查找
    Linux-Varnish缓存
    Linux-部署Hadoop环境
    Linux-部署MFS分布式文件系统
    Linux-部署Jumpserver跳板机
    Linux-部署Heartbeat高可用
    Linux-Mysql5.7之字段约束,索引,外键
    Linux-Mysql常用命令(下)
    Linux-Mysql常用命令(上)
    Python-常用模块详解
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7101642.html
Copyright © 2020-2023  润新知