内容描述
给定一个整数数组,返回两个数字的索引,使它们相加到一个特定的目标。
您可以假设每个输入都有一个解决方案,并且不能两次使用同一个元素。
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
思路 1
**- 时间复杂度: O(N)**- 空间复杂度: O(N)**
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> lookup = new HashMap<>();
int[] res = new int[2];
for (int i = 0; i < nums.length; i++) {
if (lookup.containsKey(target - nums[i])) {
res = new int[] { lookup.get(target - nums[i]), i };
break;
} else {
lookup.put(nums[i], i);
}
}
return res;
}
}