Middle-题目120:179. Largest Number

原创 2016年05月31日 20:11:04

Middle-题目120:179. 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.
题目大意:
给出一串由非负数组成的数组,求出连缀而成的最大整数。
注意:这个结果可能非常大,所以返回一个字符串。
题目分析:
观察例子,最大的数的排列顺序分别为9,5,34,3,30,观察到任意两个元素a和b,若a在b的前面则ab连缀的数一定比ba连缀的数大。据此自定义一个排序算法对数组排序并按序连缀即可。
源码:(language:java)

public class Solution {
    private class MyComparator implements Comparator<Integer> {
        public int compare(Integer o1, Integer o2) {
            // TODO Auto-generated method stub
            String s1=o1.toString()+o2.toString();
            String s2=o2.toString()+o1.toString();
            return s2.compareTo(s1);
        }
    }
    public String largestNumber(int[] nums) {
        List<Integer> list = new ArrayList<Integer>();
        for(int num:nums)
            list.add(num);
        Collections.sort(list, new MyComparator());
        String result = "";
        for(Integer i:list)
            result+=String.valueOf(i);
        if(result.startsWith("00"))
            result = "0";
        return result;
    }
}

成绩:
123ms,beats 64.21%,众数123ms,6.42%
Cmershen的碎碎念:
本题的关键在于找到合适的排序规则,一开始想到的是按字典序排列,但不能处理34>3>30的问题,后又想到补全字符串,但太慢。最后发现只要比较连缀结果的大小即可。by the way,lambda表达式咋写?我看到的ac代码大多用的是匿名类。

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

相关文章推荐

[LeetCode]179.Largest Number

【题目】 Given a list of non negative integers, arrange them such that they form the largest number...

179. Largest Number

Given a list of non negative integers, arrange them such that they form the largest number. For exa...

LeetCode题解(Week2):179. Largest Number

原题目 Given a list of non negative integers, arrange them such that they form the largest number. Fo...

LeetCode(179) Largest Number

题目如下: Given a list of non negative integers, arrange them such that they form the largest number. F...

leetcode_[python/C++] 179. Largest Number(数字组合成最大数)

题目链接 【题目】 Given a list of non negative integers, arrange them such that they form the largest numb...

Leetcode 179. Largest Number

Given a list of non negative integers, arrange them such that they form the largest number.For examp...

179.Largest Number

近期开始在LeetCode上开始刷题,第一道题是Largest Number,题目内容如下: Given a list of non negative integers, arrange them...

Leetcode 179 Largest Number 构造最大数字

给出一组非负数字,对它们进行整理排列使它们构成最大的数字。例如,给出[3, 30, 34, 5, 9],可以构成的最大的数字是9534330。

<LeetCode OJ> 179. Largest Number

179. Largest Number My Submissions Question Total Accepted: 37152 Total Submissions: 208760 Diff...

leetcode179. Largest Number

179. Largest NumberGiven a list of non negative integers, arrange them such that they form the large...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)