zoukankan      html  css  js  c++  java
  • [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();
        }
    }
    

      

  • 相关阅读:
    HDU 3033 I love sneakers!
    HDU 1712 ACboy needs your help
    FZU 1608 Huge Mission
    HDU 3394 Railway
    【MySQL】20个经典面试题,全部答对月薪10k+
    mysql故障解决笔记
    mysql 索引类型
    linux禁用锁定和解除解锁用户账号的方法
    Linux服务器制定mysql数据库备份的计划任务
    网站服务器安全防范小知识
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7101642.html
Copyright © 2011-2022 走看看