码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 179 Largest Number

时间:2015-06-06 19:29:47      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

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.

解题思路:

先把int数组转为String,然后做一个比较器,这里有一个小技巧可以用 (o2 + o1).compareTo(o1 + o2)作为比较器,可以将"大数字"放到前面,然后按照比较器的顺序输出即可,JAVA实现如下:

    public String largestNumber(int[] nums) {
    	String[] str=new String[nums.length];
    	for(int i=0;i<nums.length;i++)
    		str[i]=String.valueOf(nums[i]);
        Comparator<String> comp = new Comparator<String>() {
            public int compare(String o1, String o2) {
                return (o2 + o1).compareTo(o1 + o2);   
            }
        };
        Arrays.sort(str, comp);
        if (str[0].equals("0"))
            return "0";
        StringBuilder sb=new StringBuilder();
        for (String s : str)
        	sb.append(s);
        return sb.toString();
    }

 

Java for LeetCode 179 Largest Number

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/4557087.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!