CodeSprout程式萌芽
困難第 278 題 · 標記分組尾值
CodeSprout 官方2026/10/04 00:19
官方解答 · 置頂Java

官方解答|標記分組尾值

官方解答|標記分組尾值

解題思路

Key 以「將字串以 Locale.ROOT 轉小寫,忽略大小寫差別」及非負餘數 Math.floorMod(nums[i], 3) 為兩個欄位。equals 與 hashCode 使用同兩欄位;LinkedHashMap 保存首次鍵順序,每群對原值計算尾值,再按反向首次鍵順序輸出統計值。

正確性與邊界

分組保留群內原順序與重複值;負數餘數使用 floorMod,不能改用 %。兩個欄位都相同才合群,空資料回傳 []。

複雜度

平均時間 O(n),額外空間 O(n),g 為群數。

公開範例

輸入 {"labels": ["a", "A"], "nums": [1, 2]},依上述步驟得到 [2, 1]。

下方程式可直接取代起始碼;使用 Java 11,入口為 Solution.solve。

CodeSprout 官方解答 · 題意分析、解題步驟與完整參考程式

import java.util.*;

public class Solution {
    private static int aggregate(List<Integer> values) {
        return values.isEmpty() ? 0 : values.get(values.size()-1);
    }
    private static class Key {
        final String label;
        final int remainder;
        Key(String label, int remainder) { this.label=label; this.remainder=remainder; }
        public boolean equals(Object other) {
            if (this == other) return true;
            if (!(other instanceof Key)) return false;
            Key key=(Key) other;
            return remainder == key.remainder && label.equals(key.label);
        }
        public int hashCode() { return Objects.hash(label,remainder); }
    }

    public static List<Integer> solve(String[] labels, int[] nums) {
        Map<Key,List<Integer>> groups = new LinkedHashMap<>();
        for (int i=0; i<nums.length; i++) {
            Key key = new Key(labels[i].toLowerCase(Locale.ROOT), Math.floorMod(nums[i],3));
            groups.computeIfAbsent(key, ignored -> new ArrayList<>()).add(nums[i]);
        }
        List<Integer> result = new ArrayList<>();
        for (List<Integer> values : groups.values()) result.add(aggregate(values));
        Collections.reverse(result);
        return result;
    }
}

留言討論 0