一、题目
二、代码实现
1、双层循环
class Solution {
public int[] twoSum(int[] nums, int target) {
//若数组长度为2,且相加为target,则直接返回[0,1]
if (nums.length == 2 && (nums[0] + nums[1] == target)){
return new int[]{0,1};
}else if (nums.length > 2){
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 null;
}
}
2、哈希
class Solution {
public int[] twoSum(int[] nums, int target) {
//存哈希
Map<Integer,Integer> hash = new HashMap<>();
for (int i = 0; i < nums.length; i++){
int other = target - nums[i];
if(hash.containsKey(other)){
//如果hash中包含了此key值,返回其value值
int j = hash.get(other);
return new int[]{j,i};
}else{
//将<nums[i],i>添加至hash
hash.put(nums[i],i);
}
}
return null;
}
}