最佳人选 题解 | 豆包MarsCode AI刷题

63 阅读3分钟

刷题地址

问题理解

  1. 性格密码维度:每个人的性格可以通过 M 个维度来描述,每个维度分为 A, B, C, D, E 五种类型。
  2. 性格差异计算:同一维度内,字母距离越近,性格类型差异越小。比如,A 和 B 的差异为 1,A 和 D 的差异为 3
  3. 不相容性格类型AEBDCEBE 为不相容性格类型,差异值设为无穷大(无法匹配)。
  4. 匹配条件:如果某一维度存在不相容性格类型,则表示两个士兵性格完全不匹配。
  5. 最佳匹配:对于符合匹配条件的士兵,差异值总和越小表示匹配程度越高。

代码思路解析

1. 初始化

int minDifference = Integer.MAX_VALUE;
List<String> bestMatches = new ArrayList<>();
  • minDifference 初始化为 Integer.MAX_VALUE,用于记录最小的差异值。
  • bestMatches 是一个列表,用于存储所有与目标性格密码差异最小的士兵性格密码。

2. 遍历每个士兵的性格密码

for (String soldier : array) {
    int totalDifference = 0;
    boolean isIncompatible = false;
  • 遍历 array 中的每个士兵性格密码。
  • totalDifference 用于累加每个维度的差异值。
  • isIncompatible 用于标记是否存在不相容性格类型。

3. 计算每个维度的差异值

for (int i = 0; i < m; i++) {
    char targetChar = target.charAt(i);
    char soldierChar = soldier.charAt(i);
    // 检查是否为不相容性格类型
    if ((targetChar == 'A' && soldierChar == 'E') ||
        (targetChar == 'E' && soldierChar == 'A') ||
        (targetChar == 'B' && soldierChar == 'D') ||
        (targetChar == 'D' && soldierChar == 'B') ||
        (targetChar == 'C' && soldierChar == 'E') ||
        (targetChar == 'E' && soldierChar == 'C') ||
        (targetChar == 'B' && soldierChar == 'E') ||
        (targetChar == 'E' && soldierChar == 'B')) {
        isIncompatible = true;
        break;
    }
    // 计算字母之间的差异值
    int difference = Math.abs(targetChar - soldierChar);
    totalDifference += difference;
}
  • 遍历每个维度的字符。
  • 检查是否存在不相容性格类型,如果存在则将 isIncompatible 设为 true,并跳出循环。
  • 计算字母之间的差异值,并累加到 totalDifference 中。

4. 更新最佳匹配

if (isIncompatible) {
    continue;
}
if (totalDifference < minDifference) {
    minDifference = totalDifference;
    bestMatches.clear();
    bestMatches.add(soldier);
} else if (totalDifference == minDifference) {
    bestMatches.add(soldier);
}
  • 如果存在不相容性格类型,跳过该士兵。
  • 如果当前士兵的总差异值小于 minDifference,更新 minDifference,并清空 bestMatches,将当前士兵加入 bestMatches
  • 如果当前士兵的总差异值等于 minDifference,将当前士兵加入 bestMatches

5. 返回结果

StringBuilder sb = new StringBuilder();
for (int i = 0; i < bestMatches.size(); i++) {
    sb.append(bestMatches.get(i));
    if (i != bestMatches.size() - 1) {
        sb.append(" ");
    }
}
if (bestMatches.isEmpty()) {
    return "None";
}
return sb.toString();
  • 使用 StringBuilderbestMatches 中的士兵性格密码拼接成一个字符串。
  • 如果 bestMatches 为空,返回 "None"
  • 否则,返回拼接后的字符串。

总结

通过这个问题的解决过程,我学到了以下几点:

  1. 数据结构的选择
    • 在处理复杂逻辑时,选择合适的数据结构可以大大简化代码。例如,使用 Map 来存储不相容性格类型,可以避免冗长的 if 语句。
  1. 代码的可读性和维护性
    • 代码的可读性和维护性非常重要。通过使用更直观的数据结构和方法,可以使代码更易于理解和维护。
  1. 根据题目要求优化代码
    • 在编写代码时,要仔细阅读题目要求,并根据要求优化代码。例如,题目要求返回一个士兵性格密码,可以直接返回第一个最佳匹配的士兵性格密码,而不是拼接所有最佳匹配的士兵性格密码。