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].
class Solution { public int[] twoSum(int[] nums, int target) { //定义一个map集合来存储数组中值(键)和该值对应的下标(值) Map<Integer,Integer> map=new HashMap<>(); //遍历数组 for(int i=0;i<nums.length;i++){ //如果集合中存在目标值减去当前值所得的数 //则将所得数的下标和当前数的下标存入新数组,并返回结果 if(map.containsKey(target-nums[i])){ return new int[]{map.get(target-nums[i]),i}; } //如果集合中不存在目标值减去当前值所得的数 //就将当前数存入集合中 map.put(nums[i],i); } //数组中没有符合条件的数值,返回null return null; } }