第一次代码:37ms
public 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(nums[i]+nums[j] == target)
return new int[]{i, j};
}
}
return null;
}
}
思想:到目前为止是否存在------------比如 i = 10,表示,到时为止,是否能得到target
第二次代码:7ms
public class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> valKeyMap = new HashMap<>();
for(int i = 0; i < nums.length; i++){
if(valKeyMap.containsKey(target - nums[i])){
return new int[]{valKeyMap.get(target - nums[i]), i};
}
valKeyMap.put(nums[i], i);
}
return new int[]{0, 0};
}
}