[Leetcode][001] Two Sum (Java)

时间:2023-03-09 00:17:14
[Leetcode][001] Two Sum (Java)

题目在这里: https://leetcode.com/problems/two-sum/

【标签】Array; Hash Table

【个人分析】

  这个题目,我感觉也可以算是空间换时间的例子。如果是O(n^2)的那种思路,就是对于一个数字,去扫剩下的所有数字,看有没有能够加起来和为target的组合。但是如果加入一个哈希表,我们扫过的数字都可以记录下来。

我用的是 (target - number) 作为key, 用number在nums中的 index 作为 value, 遇到一个新的数字number,如果它存在于map 中(说明我们先前遇到过target - number),那么我们就是找到结果了。

 public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Map<Integer, Integer> indexMap = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
int number = nums[i];
if (indexMap.containsKey(number)) {
// found the two numbers we are looking for!
// ! required result is not zero-based indexed, but 1-based
result[0] = 1 + indexMap.get(number);
result[1] = 1 + i;
break;
} else {
// put the number we are expecting into the map
indexMap.put(target - number, i);
}
}
return result;
} }