1. 两数之和 - LeetCode
1. 两数之和
最直接的方法
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;
}
}
使用Map
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后面要写清楚数组长度
- 初始化的值用大括号{}括起来

浙公网安备 33010602011771号