资讯动态

二刷hot100-1.两数之和

发布时间:2026/8/20 0:07:25 来源:尧图企业网站定制
使用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; } }

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价