官方解答 · 置頂Java
官方解答|策略讀值總和
官方解答|策略讀值總和
解題思路
用 Rule 定義共同介面。符合「介於負二與三」選 MatchRule,套 x;其他選 OtherRule,套 x/2。經 Rule 參考呼叫 apply,依序保留或加總每筆結果。
正確性與邊界
分支判斷原值,每個元素恰好選一種策略。結果保留重複值;空輸入的清單為 []、總和為 0。
「介於負二與三」包含兩個端點,即 -2 <= x && x <= 3;x 指當前原始數值。
複雜度
時間 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/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 = (x >= -2 && x <= 3) ? matchRule : otherRule;
values.add(rule.apply(x));
}
return aggregate(values);
}
}
留言討論 0
登入 後就能留言,一起討論不同的寫法。