官方解答 · 置頂Java
官方解答|策略讀值清單
官方解答|策略讀值清單
解題思路
用 Rule 定義共同介面。符合「絕對值至少三」選 MatchRule,套 x;其他選 OtherRule,套 x*x。經 Rule 參考呼叫 apply,依序保留或加總每筆結果。
正確性與邊界
分支判斷原值,每個元素恰好選一種策略。結果保留重複值;空輸入的清單為 []、總和為 0。
複雜度
時間 O(n),額外空間 O(n)。
公開範例
輸入 {"nums": [1]},依上述步驟得到 [1]。
下方程式可直接取代起始碼;使用 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; }
}
private static class OtherRule implements Rule {
public int apply(int x) { return x*x; }
}
public static List<Integer> 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 values;
}
}
留言討論 0
登入 後就能留言,一起討論不同的寫法。