回首上一次leetcode的博客,还是2019年的事情,这一年半以来发生了很多事情
从今天开始用Java重新刷leetcode,每天坚持打卡记录,希望能找回初心吧!
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hashtable = new HashMap<>();
for (int i = 0; i < nums.length; ++i) {
if (hashtable.containsKey(target - nums[i])) {
return new int[]{hashtable.get(target - nums[i]), i};
}
hashtable.put(nums[i], i);
}
return new int[0];
}
}
题目很简单,主要目的是熟悉Java的HashMap的使用,
HashMap的创建 Map<Integer,Integer>hashtable = new HashMap<>()
HashMap的常用方法: constainsKey, get, put