class Solution {
public int[] twoSum(int[] nums, int target) {
/* 双层循环解法
for(int i=0;i<nums.length;i++) {
for(int j=i+1;j<nums.length;j++) {
if(nums[i]+nums[j]==target) {
return new int[]{i,j};
}
}
}
return new int[0];//注意此处return new int[]
}*/
//↓哈希解法
int len=nums.length;
Map<Integer,Integer> hashMap = new HashMap<>(len-1);//初始化哈希表时,指定哈希表的容量
hashMap.put(nums[0],0);//将第一个元素放入哈希表,因为肯定没有与之对应的值,所以可以直接放入
for(int i=1;i<len;i++){
int another = target-nums[i];
if(hashMap.containsKey(another)){//判断哈希表中是否存在another这个值
return new int[]{i,hashMap.get(another)};//get()返回another这个值的索引位置
}
hashMap.put(nums[i],i);
}
return new int[0];
}
}
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例 2:
输入:nums = [3,2,4], target = 6
输出:[1,2]
示例 3:
输入:nums = [3,3], target = 6
输出:[0,1]