题目: https://leetcode-cn.com/problems/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/
解法一: 暴力解法
根据题目的意思, 每个人和对应时间的关系类似于Map的关系(一对多), 所以, 该题使用哈希表可以解决.
import java.math.BigDecimal;
class Solution {
public List<String> alertNames(String[] keyName, String[] keyTime) {
List<String> ans = new ArrayList<>();
Map<String, List<Float>> namesTime = new HashMap<>();
int len = keyName.length;
for (int i = 0; i < len; i++) {
String currTime = keyTime[i];
if (!namesTime.containsKey(keyName[i])) {
List<Float> tmp = new ArrayList<>();
tmp.add(timeToFloat(keyTime[i]));
namesTime.put(keyName[i], tmp);
continue;
}
namesTime.computeIfPresent(keyName[i], (s, floats) -> {
floats.add(timeToFloat(currTime));
return floats;
});
}
for (Map.Entry entry : namesTime.entrySet()) {
List<Float> value = (List<Float>) entry.getValue();
value.sort((o1, o2) -> Float.compare(o1, o2));
for (int i = 0; i < value.size() - 2; i++) {
// 注意: 如果直接浮点数相减会不准确, 这里需要保留2位小数
BigDecimal bigDecimal = new BigDecimal(value.get(i) - value.get(i + 2));
Float period = Math.abs(bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue());
if (period.compareTo(1f) <= 0) {
ans.add((String) entry.getKey());
break;
}
}
}
ans.sort(Comparator.naturalOrder());
return ans;
}
private float timeToFloat(String time) {
return Float.valueOf(time.replace(":", "."));
}
}