← 從零開始學 Java
第 81 課,共 88 課 · 10 XP
演算法
理論與題目說明
機器翻譯,尚未經母語人士審閱。
類別 Collections 有給集合用的現成演算法:
List<Integer> l = new ArrayList<>(List.of(5, 3, 9, 3, 1));
Collections.max(l), Collections.min(l) // 9, 1
Collections.frequency(l, 3) // 2
Collections.reverse(l) // [1, 3, 9, 3, 5]
Collections.swap(l, 0, 4)
Collections.rotate(l, 2) // 向右循環位移 2 格
Collections.sort(l)
Collections.binarySearch(l, 9) // 在排序好的串列裡的索引(O(log n))
Collections.nCopies(3, "ab") // [ab, ab, ab]
Collections.unmodifiableList(l) // 「唯讀」的包裝
陣列有對應的 Arrays:sort、binarySearch、fill、equals。
在沒排序的串列上,binarySearch 會回傳垃圾。找不到元素時會回傳負數
-(插入位置) - 1。
題目。 讀入數字。輸出:最大值和最小值、最大值出現幾次、rotate 1 格之後的
串列,接著是排序好的串列,以及在其中用 binarySearch 找數字 7 的索引
(找不到是 沒有)。