LeetCode-001-两数之和

思路
使用HashMap来记录已经遍历过数
要点:HashMap的使用
- 创建:HashMap<key,value> map=new HashMap();
- 常用函数:get(key)(获得value),containsKey(key)(是否含有键),put(key,value)
代码
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map=new HashMap();
for(int i=0;i<nums.length;i++){
if(map.containsKey(target-nums[i])){
return new int[]{map.get(target-nums[i]),i};
}
map.put(nums[i],i);
}
return null;
}
}
这篇博客介绍了如何利用HashMap数据结构解决LeetCode中的001题——两数之和。通过遍历数组,将每个数及其索引入HashMap,然后检查目标值减去当前数是否在HashMap中,从而找到答案。这种方法有效地减少了查找时间,提高了算法效率。
122

被折叠的 条评论
为什么被折叠?



