给定一个整数数组nums和一个整数目标值target,请你在该数组中找出和为目标值target的两个整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。

思路:设置一个map存放未匹配上的元素值和下标,遍历数组,如果map中未找到target减去当前元素的值,那么就将当前元素存放在map中。
方法:
public class Solution{ public int[] twoSum(int[] nums,int target){ if(null==nums||nums.length<2){ return null; } Map<Integer,Integer> map=new HashMap(); int one,two; for(int i=0;i<nums.length;i++){ one=nums[i]; two=target-one; if(map.containsKey(two)){ Integer index=map.get(two); return new int[]{index,i}; }else{ map.put(one,i); } } return null; } }
posted on
浙公网安备 33010602011771号