LeetCode1-两数之和

题目链接

英文链接:https://leetcode.com/problems/two-sum/

中文链接:https://leetcode-cn.com/problems/two-sum/

题目详述

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

示例:

1
2
3
4
给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

题目详解

本题有多种解答方法,比较快的做法是采用哈希表。运用哈希表的复杂度分析如下:

  • 时间复杂度:O(n), 我们只遍历了包含有 n 个元素的列表一次。在表中进行的每次查找只花费 O(1) 的时间。
  • 空间复杂度:O(n), 所需的额外空间取决于哈希表中存储的元素数量,该表最多需要存储 n 个元素。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.util.HashMap;
import java.util.Map;

public class LeetCode_00001 {

public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; ++i) {
int t = target - nums[i];
if (map.containsKey(t)) {
return new int[] {map.get(t), i};
}
map.put(nums[i], i);
}
return null;
}
}