Given an array of integers, return indices of the two numbers such that they add up to a specific target.
time:o(n) space:o(n)
time:o(n) space:o(n)
最初做法用2个循环,但是用一个循环会节省一点时间,虽然时间复杂度一样。
<span style="font-size:14px;"> public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
int len=nums.length;
for(int i=0;i<len;i++){
if(map.containsKey(target-nums[i]))
return new int[]{map.get(target-nums[i]),i};
else
map.put(nums[i],i);
}
return new int[]{-1,-1};
}</span>