阅读设置
界面、侧栏和正文分别调整,自动保存。
主题切换
界面、侧栏和正文分别调整,自动保存。
问题描述: 给定一个整数数组 nums 和一个整数目标值 target,请在该数组中找出和为目标值 target 的那两个整数,并返回它们的数组下标。
示例:
输入:nums = [2,7,11,15], target = 9 输出:[0,1] 解释:因为 nums[0] + nums[1] == 9,所以返回 [0, 1]。
target - 当前元素。package lc0_lc99.lc1;
import java.util.HashMap;
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
int[] res = new int[2];
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i])) {
res[0] = map.get(nums[i]);
res[1] = i;
}
map.put(target - nums[i], i);
}
return res;
}
}class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<>();
// 双指针同时从首尾向中间遍历
for(int i = 0, j = nums.length - 1;i <= j;i++,j--){
// 检查左侧元素是否已有匹配项
if(map.containsKey(target - nums[i])){
return new int[]{i,map.get(target - nums[i])};
}
map.put(nums[i],i); // 存入左侧元素
// 检查右侧元素是否已有匹配项
if(map.containsKey(target - nums[j])){
return new int[]{j,map.get(target - nums[j])};
}
map.put(nums[j],j); // 存入右侧元素
}
return new int[]{0,0};
}
}