CodeSprout程式萌芽
中等第 242 題 · 策略讀值總和
CodeSprout 官方2026/10/04 00:19
官方解答 · 置頂Java

官方解答|策略讀值總和

官方解答|策略讀值總和

解題思路

用 Rule 定義共同介面。符合「絕對值至少三」選 MatchRule,套 x*x;其他選 OtherRule,套 x/2。經 Rule 參考呼叫 apply,依序保留或加總每筆結果。

正確性與邊界

分支判斷原值,每個元素恰好選一種策略。結果保留重複值;空輸入的清單為 []、總和為 0。

複雜度

時間 O(n),額外空間 O(n)。

公開範例

輸入 {"nums": [1]},依上述步驟得到 0。

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

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

import java.util.*;

public class Solution {
    private interface Rule { int apply(int x); }
    private static class MatchRule implements Rule {
        public int apply(int x) { return x*x; }
    }
    private static class OtherRule implements Rule {
        public int apply(int x) { return x/2; }
    }
    private static int aggregate(List<Integer> values) {
        int answer = 0;
        for (int x : values) answer += x;
        return answer;
    }

    public static int solve(int[] nums) {
        Rule matchRule = new MatchRule(), otherRule = new OtherRule();
        List<Integer> values = new ArrayList<>();
        for (int x : nums) {
            Rule rule = (Math.abs(x) >= 3) ? matchRule : otherRule;
            values.add(rule.apply(x));
        }
        return aggregate(values);
    }
}

留言討論 0