官方解答 · 置頂Java
官方解答|標記分組最低值
官方解答|標記分組最低值
解題思路
Key 以「將字串以 Locale.ROOT 轉小寫,忽略大小寫差別」及非負餘數 Math.floorMod(nums[i], 4) 為兩個欄位。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) {
if (values.isEmpty()) return 0;
int answer = values.get(0);
for (int x : values) answer = Math.min(answer, x);
return answer;
}
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],4));
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
登入 後就能留言,一起討論不同的寫法。