题目
解法
①数组, 哈希表 + 循环
class Solution{
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hashmap = new HashMap<Integer, Integer>();
for(int i = 0; i < nums.length; i++){
int num = target - nums[i];
if(hashmap.containsKey(num)){
return new int[]{i, hashmap.get(num)};
}
hashmap.put(nums[i], i);
}
return new int[0];
}
}
②数组 + 暴力法
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i = 0; i < nums.length - 1; 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];
}
}