1.Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
来源:力扣(LeetCode)
解法:HashMap 插入和查找的时间复杂度都为 O(1)
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map = new HashMap<>();
int[] arr = new int[2];
for (int i = 0; i < nums.length; i++) {
int latter = target - nums[i];
if (map.get(latter) != null) {
arr[0] = map.get(latter);
arr[1] = i;
return arr;
}
map.put(nums[i],i);
}
throw new IllegalArgumentException("无两数之和等于 target")
;
}
}
定义 map 为 HashMap, 题目仅需要求得第一个满足的解,故输出数组为一对索引,因此输出数组大小为2。
遍历原数组,若 map 中没有 target - nums[i] 的值,则将正在遍历的数插入至 map 中,因 map 是依靠 key 来寻找 value,故 nums 数组的值为 key、索引为 value。
若存在target - nums[i] 的值,将此时的下标 i 与 map 对应的 value 放入输出数组中。