2026/8/18 18:22:50

二刷hot100-1.两数之和

二刷hot100-1.两数之和 使用map存放遍历到的当前数组元素nums[i]利用map特性检索当前的target - nums[i]是否存在若存在则存入当前结果数组res否则继续下一次遍历检索。map中key存数值value存索引因为是根据数值查找索引最终结果也是返回索引。class Solution { public int[] twoSum(int[] nums, int target) { MapInteger,Integer map new HashMap(); int[] res new int[2]; for(int i 0;i nums.length;i){ int temp target - nums[i]; if(map.containsKey(temp)){ res[0] i; res[1] map.get(temp); // return res; } map.put(nums[i],i); } return res; } }