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].
题意:
给定数组,若数组中两个元素之和等于给定的target值,返回这两个元素的index
思路:
每遍历到一个数字,就去HashMap容器里面查看 ( target - 该数字 )已经在HashMap里。
在有以下需求:(1)查找指定元素是否存在 (2)通过A元素找B元素
首先考虑用HashMap。
可以把HashMap看成一个容器,将数据扔到该容器中。
该容器有很多功能键。
但常用的功能仅这么几个:
map.put(k, v)
map.containsKey(k)
map.get(k)
map.remove(k)
注意到,HashMap都是对key的操作!!!value榭寄生般依附于key,无所作为。
nums = [2, 7, 11, 15] HashMap
K V i 2 - 0 i 7 - 1 check whether map containsKey of target - nums[i] i 11- 2 i 15- 3
代码:
1 class Solution { 2 public int[] twoSum(int[] nums, int target) { 3 HashMap<Integer, Integer> map = new HashMap<>(); 4 for(int i = 0 ; i < nums.length; i++){ 5 if(map.containsKey(target - nums[i])){ 6 return new int[]{i, map.get(target - nums[i])}; 7 }else{ 8 map.put(nums[i], i); 9 } 10 } 11 return null; 12 }