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.
题解与理解
- 题意大致是:给定一个数组,和一个目标数字target;找出数组中和为目标数字target的两个数
解题用了一个HashMap;key为该数字target-nums[i],value为nums[i];
对数组进行遍历,如果map中不存在与其相等的key,则将该数字存入map;
当遍历的数字发现map中存在与其对应的key时,则说明当前遍历数字与前面遍历过的某数字相加为target;
此时获取map中的该数字,存储到result中,并return;
解题源码
1 | public class Solution { |