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

Largest Number Leetcode

时间:2017-01-27 07:18:49      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:lis   orm   string   tostring   append   style   content   equal   ++   

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.

 

这道题就是有些情况不太好想到,而且两个数字比的时候我写的有点复杂了,一开始觉得直接连起来比太耗时,写完了发现好像是一样的。。。= =我的反而要想。。。

注意一下第一个是0的情况。

public class Solution {
    public String largestNumber(int[] nums) {
        StringBuilder sb = new StringBuilder();
        if (nums == null) {
            return null;
        }
        String[] n = new String[nums.length];
        for (int i = 0; i < nums.length; i++) {
            n[i] = String.valueOf(nums[i]);
        }
        Arrays.sort(n, new Comparator<String>(){
            public int compare(String a, String b) {
                int i = 0;
                int j = 0;
                int com = 0;
                while (com < a.length() + b.length()) {
                    char first = i < a.length() ? a.charAt(i) : a.charAt(i % a.length());
                    char second = j < b.length() ? b.charAt(j) : b.charAt(j % b.length());
                    i++;
                    j++;
                    com++;
                    if (first == second) {
                        continue;
                    }
                    return second - first;
                }
                return 0;
            }
        });
        if (n[0].equals("0")) {
            return new String("0");
        }
        for (int i = 0; i < n.length; i++) {
            sb.append(n[i]);
        }
        return sb.toString();
    }
}

top solution和我的思路一样,不过是连起来比较的。。。简单很多。。。

Largest Number Leetcode

标签:lis   orm   string   tostring   append   style   content   equal   ++   

原文地址:http://www.cnblogs.com/aprilyang/p/6353301.html

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