标签:target class ++ pre 双指针 contains targe integer problem
本题可以有两种方法,一种先排序,再用双指针法找到两数。另一种利用哈希表存储值对应的下标,如果在表中找到target-nums[i]对应的值,则直接输出
Java
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> hash = new HashMap<>();
for(int i = 0 ; i < nums.length ; i++){
if(hash.containsKey(target-nums[i])){
return new int[]{hash.get(target-nums[i]),i};
}
hash.put(nums[i],i);
}
return null;
}
}
标签:target class ++ pre 双指针 contains targe integer problem
原文地址:https://www.cnblogs.com/xkf97/p/13149932.html