[一天至少一题直到ICPC开赛028]解题:Sort! Sort!! and Sort!!!(1/19)

Sort! Sort!! and Sort!!!

题目连结

最近都在摸鱼,进度点落后

解题

按照规则,比较 ==> 结束
取余

先放小的
如果相同

先放基数,然后偶数

都是基数==>先大后小
都是偶数==>先小后大

code (java)

    import java.util.*;    public class Sort_Sort_and_Sort {        static int M, n;        public static void main(String[] args) {            Scanner sc = new Scanner(System.in);            while (true) {                n = sc.nextInt();                M = sc.nextInt();                System.out.println(n + " " + M);                if (M == 0 && n == 0) {                    break;                }                ArrayList<Integer> array = new ArrayList<Integer>();                for (int i = 0; i < n; i++) {                    array.add(sc.nextInt());                }                Collections.sort(array, new cmp());                for (int it : array) {                    System.out.println(it);                }            }            sc.close();        }        static class cmp implements Comparator<Integer> {            @Override            public int compare(Integer num1, Integer num2) {                boolean isOdd1 = num1 % 2 != 0;                boolean isOdd2 = num2 % 2 != 0;                // 先排小的再排大的                if (num1 % M != num2 % M) {                    return Integer.compare(num1 % M, num2 % M);                }                // 基数先,由大到小                if (isOdd1 && isOdd2) {                    return Integer.compare(num2, num1);                }                // 偶数后,由小到大                else if (!isOdd1 && !isOdd2) {                    return Integer.compare(num1, num2);                }                // 其他情况,基数优先                return isOdd1 ? -1 : 1;            }        }    }

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章