首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

HDU 2020 絕對值排序:Java 實現與自定義比較器

     編輯:關於C++

題目大意

輸入多組測試數據,每組第一個整數 n (≤100),後跟 n 個整數。按絕對值從大到小排序輸出。保證絕對值互不相同。n=0 結束輸入。

解法:自定義比較器

Java 中使用 Arrays.sort 搭配 Comparator,比較邏輯為 |b| - |a|(降序)。

完整 Java 代碼


import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            int n = in.nextInt();
            if (n == 0) break;
            Integer[] arr = new Integer[n];
            for (int i = 0; i < n; ++i) arr[i] = in.nextInt();
            Arrays.sort(arr, (a, b) -> Math.abs(b) - Math.abs(a));
            for (int i = 0; i < n; ++i) {
                if (i) System.out.print(' ');
                System.out.print(arr[i]);
            }
            System.out.println();
        }
    }
}

關鍵點

  • 使用 Integer[] 而非 int[] 以支援 Comparator
  • Lambda 表達式 (a, b) -> Math.abs(b) - Math.abs(a) 實現降序
  • 輸入以 n=0 終止,Scanner.hasNext() 處理多組數據

樣例

輸入:
3 3 -4 2
4 0 1 2 -3
0
輸出:
-4 3 2
-3 2 1 0
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved