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

Largest Number

时间:2015-05-06 20:59:18      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/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.

解题思路:

这题目似乎比较难,难处在于一眼可以看出思路,但是无法写出解法。所谓talk is cheap, show me the code。

感觉很像基数排序,但是确实从低位补齐,即把低位和高位对比。网友说,用Comparetor,一语点开天机。这个问题无非就是一个将nums排序的问题,然后将结果按顺序contact,输出。

问题是,如何定义两个数字的大小关系呢?开始考虑按位对比,但是比想象的要复杂。比如321和32,323和32。后来发现,两个数字的组合,就两种可能,S1S2或者S2S1,直接比较大小不就可以了?

还有个问题,当所有数字都是0的时候,不要输出00,而是0。

public class Solution {
    public class Compare implements Comparator<String>{
        public int compare(String s1, String s2){
            // int i = 0, j = 0;
            // while(i < s1.length() && j < s2.length() && s1.charAt(i) == s2.charAt(j)) {
            //     if(i != s1.length() - 1) {
            //         i++;
            //     }
            //     if(j != s2.length() - 1) {
            //         j++;
            //     }
            //     if(i == s1.length() - 1 && j == s2.length() - 1) {
            //         return s1.charAt(i) - s2.charAt(j);
            //     }
            // }
            // return s1.charAt(i) - s2.charAt(j);
            String new1 = s1 + s2;
            String new2 = s2 + s1;
            for(int i = 0; i < new1.length(); i++) {
                if(new1.charAt(i) != new2.charAt(i)) {
                    return new1.charAt(i) - new2.charAt(i);
                }
            }
            return 0;
        }
    }
    
    public String largestNumber(int[] nums) {
        if(nums.length == 0) {
            return new String("0");
        }
        String result = "";
        String[] numsStr = new String[nums.length];
        for(int i = 0; i < nums.length; i++) {
            numsStr[i] = String.valueOf(nums[i]);
        }
        Arrays.sort(numsStr, new Compare());
        for(int i = numsStr.length - 1; i >= 0; i--) {
            result += numsStr[i];
        }
        //如果是[0,0]就返回0,而不是00
        for(int i = 0; i < nums.length; i++) {
            if(nums[i] != 0) {
                return result;
            }
        }
        return "0";
    }
}

自己实现一个类去实现comparetor接口,重写它的compare方法,在Merge k Sorted Lists 和 Merge Intervals 都用到过。也可以override String的compareTo方法,不过这里不好用。

这道题的总结就是,要透过题目的意思去看本质。本题实际上就是将元素按照某种规则去排序,而不是平常意义上的大小。那么这个规则就可以用一个new compare()来定义。

Largest Number

标签:

原文地址:http://www.cnblogs.com/NickyYe/p/4482523.html

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