zoukankan      html  css  js  c++  java
  • 算法:给定多个数字,把多个数字任意组合,选出组合后最大的数

    比如说 1,2,3,最大的数就是321。11,12,13最大的就是131211。如何计算呢:

    public static void main(String[] args) {
            
            String[] strs = new String[]{"9", "923", "9239"};
            
            Arrays.sort(strs, new Comparator<String>() {
                public int compare(String o1, String o2) {
                    
                    if(Math.min(o1.length(), o2.length()) == 0)
                        return 0;
                    for (int i = 0; i < Math.min(o1.length(), o2.length()) ; i++) {
                        if (!(o1.charAt(i) == o2.charAt(i)))
                            return o1.charAt(i) - o2.charAt(i);
                    }
                    return o1.length() < o2.length() ? compare(o1,
                            o2.substring(o1.length())) : compare(
                            o1.substring(o2.length()), o2);
                }
            });
            
            for (String string : strs) {
                System.out.println(string);
            }
        }

    使用一个递归。

    这题的陷阱在于如果两个数字字符串,前几个字符一样,那么决定顺序的是最早不一样的数字。

    但是如果一个包含另一个时,就需要对长的进行截断,取不重复的那一段再比较,以此类推,是一个递归。

  • 相关阅读:
    hdu4726
    hdu2709
    hdu4706
    hdu4715
    快速幂取模
    快速幂
    asp.net中页面传值
    微信小程序支付
    sql 查询重复记录值取一条
    bower使用
  • 原文地址:https://www.cnblogs.com/guangshan/p/4698826.html
Copyright © 2011-2022 走看看