Array——LeetCode——Two Sum

【学到的知识点——HashMap】
1、HashMap是链表+数组的组合方式(结合模型来思考)
数组寻址容易,插入和删除困难
链表正好相反
HashMap正好将二者互补了一下
2、对一个HashMap键值对的查找,是分为四步的
1)先根据key值计算出hash值以及h值(h值是java实现中处理得到的更优的index索引值)
2)查找table数组中的h位置,得到相应的键值对链表
3)根据key值,遍历键值对链表,找到相应的键值对,
4)从键值对中取出value值。
3、HashMap的优化
主要是对Hash算法的优化
4、Arrays是一个工具类,有很多有用的方法
【学到的知识点——数组】
1、嵌套循环怎么跳出
用return跳出
-----------------------------------------------------------------------------------------------------
【反思】
初略一看很容易就从双重循环入手来解决这道题。我们应该在想出一个办法后,紧接着想想是否还能优化,用空间换时间之类的。
-----------------------------------------------------------------------------------------------------

【Java解法】
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
HashMap<Integer, Integer> m = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
m.put(nums[i], i);
}

for(int i = 0; i < nums.length; i++) {
int t = target - nums[i];
if (m.containsKey(t) && m.get(t) != i) {
result[0] = i;
result[1] = m.get(t);
break;
}
}
return result;
}
}

猜你喜欢

转载自www.cnblogs.com/Dbbf/p/9581907.html