[LeetCode]两数之和(Two Sum)

6次阅读

共计 564 个字符,预计需要花费 2 分钟才能阅读完成。

题目描述
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
解决方案
若 a + b = c,则 c – a = b。所以只需记录所有遍历过的数,然后利用预期值 - 当前值得出的值查询是否已有记录,如果有则退出循环。
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
// 记录遍历过的数和索引
Map<Integer, Integer> map = new HashMap<>();

for (int i = 0; i < nums.length; i++) {
// 获取 target-nums[i],看是否存在,存在则表明可以相加为 target
Integer value = map.get(target – nums[i]);
if (value != null) {
res[0] = value;
res[1] = i;
break;
}
// 用键保存遍历过的数,用值保存遍历过的索引
map.put(nums[i], i);
}

return res;
}
时间复杂度:O(n) 空间复杂度:O(n) 原文地址:https://lierabbit.cn/2018/04/…

正文完
 0