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; } } }