码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Largest Number, 解题报告

时间:2015-04-05 13:22:34      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:leetcode

目录


题目

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 num数组转换为String num数组,然后对其进行排序。排序的规则如下:

例如字符串str1和str2,拼接字符串cmp1 = str1 + str2,cmp2 = str2 + str1。按照字典排序,如果cmp1 > cmp2,则str1 > str2。反之,则str1 < str2。
注意:这里可以使用Java提供的Comparator接口,然后实现字典逆序。

Cpmparator接口使用可以参考我的这篇博客:Comparator和Comparable的区别使用


AC代码

AC的代码如下:

public class Solution {
    public static String largestNumber(int[] num) {
        StringBuilder res = new StringBuilder();

        String[] numArrays = new String[num.length];
        int zeroNum = 0;
        for (int i = 0; i < num.length; i ++) {
            if (num[i] == 0) {
                zeroNum ++;
            }
            numArrays[i] = Integer.toString(num[i]);
        }

        if (zeroNum == num.length) {
            return "0";
        }

        Arrays.sort(numArrays, new NumComparator());

        for (String s : numArrays) {
            res.append(s);
        }      
        return res.toString();
    }


    private static class NumComparator implements Comparator<String> {

        @Override
        public int compare(String str1, String str2) {
            String cmp1 = str1 + str2;
            String cmp2 = str2 + str1;

            return cmp1.compareTo(cmp2) * -1;
        }

    }
}

[LeetCode]Largest Number, 解题报告

标签:leetcode

原文地址:http://blog.csdn.net/wzy_1988/article/details/44886503

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