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;
}
}
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
if(map.containsKey(nums[i])){
return new int[]{map.get(nums[i]), i};
}
map.put(target - nums[i], i);
}
return null;
}
}
这里使用HashMap进行一个映射。每到一个数nums[i],我们需要找对应的target - nums[i],那么我们就把target - nums[i]存成key,以后出现这个数,就能在map中找到。当然,因为要输出下标,就把value设置成下标。
以int类型为例
int[] intArray = new int[3]{1, 2, 3};
注意以下几点:
new后面要写清楚数组长度
原文:https://www.cnblogs.com/xiafrog/p/14278892.html