暴力穷举 (双for)
第一次for获取到当前数组,第二次for获取当前下标+1,两次for相加等于目标值则输出,不等于则进入下次循环
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(target==nums[i]+nums[j]){
return new int[]{i,j};
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
}哈希Map
首选创建哈希表,键为数组的值,值为数组下标,之后计算目标值与当前遍历值的补数,再使用containsKey(x)检查是否存在哈希表中,若有则返回补数下标与当前下标,若没有则put进入map中进入下一次遍历
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for(int i=0;i<nums.length;i++){
int x = target - nums[i];
if(map.containsKey(x)){
return new int[]{map.get(x),i};
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
}