给定一个整数数组 nums
和一个整数目标值 target
,请你在该数组中找出 和为目标值 target
的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案,并且你不能使用两次相同的元素。
你可以按任意顺序返回答案。
一、暴力遍历
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] results = new int[2];
for(int i=0;i<nums.length;i++){
for(int j=0;j<nums.length;j++){
if(i !=j){
if(target == (nums[i] + nums[j])){
results[0] = i;
results[1]=j;
}
}
}
}
return results;
}
}
二、Hash表解法
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> hashTable = new HashMap<Integer,Integer>();
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];
}
}