Largest Number

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.

思路:

  comparator<String> 基数排序

我的代码:

public class Solution {

    public String largestNumber(int[] num) {

        if(num == null || num.length == 0) return "";

        StringBuffer sb = new StringBuffer();

        HashMap<Character,List<String>> hm = new HashMap<Character,List<String>>();

        for(int i = 0; i < num.length; i++)

        {

            char c = String.valueOf(num[i]).charAt(0);

            if(hm.containsKey(c))

            {

                hm.get(c).add(String.valueOf(num[i]));

            }

            else

            {

                List<String> list = new ArrayList<String>();

                list.add(String.valueOf(num[i]));

                hm.put(c,list);

            }

        }

        for(char c = '9'; c >= '0'; c--)

        {

            if(hm.containsKey(c))

            {

                List<String> list = hm.get(c);

                Collections.sort(list, new NumberCompare());

                for(int j = 0; j < list.size(); j++)

                {

                    sb.append(list.get(j));

                }

            }

        }

        String rst = sb.toString();

        if(rst.length() != 0 && rst.charAt(0) == '0') return "0";

        return rst;

        

    }

    private class NumberCompare implements Comparator<String>

    {

        public int compare(String one, String two)

        {

            String first = one + two;

            String second = two + one;

            int len = first.length();

            int i = 0;

            while( i < len)

            {

                char onec = first.charAt(i);

                char twoc = second.charAt(i);

                if(onec == twoc)    i++;

                else if(onec > twoc) return -1;

                else return 1;

            }

            return 0;

        }

    }

}
View Code

他人代码:

public class Solution {

    public String largestNumber(int[] num) {

        if (num == null) {

            return null;

        }

        ArrayList<Integer> list = new ArrayList<Integer>();

        for (int n1: num) {

            list.add(n1);

        }

        

        Collections.sort(list, new Comparator<Integer>(){

            public int compare(Integer o1, Integer o2) {

                String s1 = "" + o1 + o2;

                String s2 = "" + o2 + o1;

                

                return s2.compareTo(s1);

            }

        });

        StringBuilder sb = new StringBuilder();

        for (int n: list) {

            sb.append(n);

        }

        if (sb.charAt(0) == '0') {

            return "0";

        }  

        return sb.toString();

    }

}
View Code

学习之处:

  • comparator的应用现状已经完全无压力了
  • 被人的代码虽然简洁,但是分开进行排序,速度更快。

你可能感兴趣的:(number)