import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * @param nums int整型一维数组 * @param target int整型 * @return int整型一维数组 */ public int[] twoSum(int[] nums, int target) { int[] result = new int[2]; // 创建HashMap存储数组元素值与对应的索引 // 键: 数组元素值, 值: 元素对应的索引 HashMap<Integer, Integer> map = new HashMap<>(); // 遍历数组,寻找目标组合 for (int i = 0; i < nums.length; i++) { // 计算当前元素需要的互补值 int complement = target - nums[i]; // 检查互补值是否已经在HashMap中 if (map.containsKey(complement)) { // 找到符合条件的两个数,返回它们的索引(注意题目要求索引从1开始) result[0] = map.get(complement) + 1; result[1] = i + 1; return result; } // 将当前元素和索引存入HashMap map.put(nums[i], i); } // 题目假设一定有解,此处返回默认数组 return result; } }