声明:本题及相关刷题笔记同步github之中,欢迎Fork & Star GitHub:https://github.com/HoqiheChen。如有不足之处,烦请改正。QQ Mail:851774342@qq.com
Description
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
Brief
两数之和。
Input
nums = [2, 7, 11, 15], target = 9,
Output
[0, 1]
Explanation
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Ideas
运用hashmap,首先将数组中所有元素的值与所处位置放入map
- 之后进行遍历,看不等于当前位置的key值是否为target‐nums[i]
- 如果是,则返回(当前位置,target‐nums[i]的位置)
Code
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map = new HashMap();
for(int i=0;i<nums.length;i++) {
map.put(nums[i], i);
}
for(int i=0;i<nums.length;i++) {
if (map.containsKey(target-nums[i])&&map.get(target-nums[i])!=i) {
return new int[]{i, map.get(target-nums[i])};
}
}
return null;
}
}
声明:本题及相关刷题笔记同步github之中,欢迎Fork & Star GitHub:https://github.com/HoqiheChen。如有不足之处,烦请改正。QQ Mail:851774342@qq.com