How can I manipulate an array to make the largest number?

前端 未结 16 2130
暖寄归人
暖寄归人 2021-01-30 02:47

Say you have an array of positive integers, manipulate them so that the concatenation of the integers of the resultant array is the largest number possible. Ex: {9,1,95,17,5}, r

16条回答
  •  攒了一身酷
    2021-01-30 03:07

    Looking at the example {5,54,56}, the proper way to order these numbers is when comparing strings A and B, we should consider lexicographic ordering of A+B with B+A.

    For example:

    • Comparing (5,54) becomes lexicographic comparison of ("554" with "545")
    • Comparing (5,56) becomes lexicographic comparison of ("556" with "565")
    • Comparing (54,56) becomes lexicographic comparison of ("5456" with "5654")

    If we sort them this way, the resulting array is {56,5,54}.

    Here's a Java implementation of this idea:

    public class LexicographicSort implements Comparator {
    
        public int compare(Integer o1, Integer o2) {
            String s1 = o1.toString();
            String s2 = o2.toString();
            return (s2+s1).compareTo(s1+s2);
        }
    
        public static void main(String[] args) {
            LexicographicSort ls = new LexicographicSort();
            Integer[] nums = {9,1,95,17,5};
            Arrays.sort(nums, ls);
            System.out.println(Arrays.toString(nums));
        }
    }
    

提交回复
热议问题