题意:给一个无序的数组找出里边两个数的和为指定数的位置
思路:
从头至尾遍历数组,每一次判断hashmap中是否有数值等于位指定数-当前数的项,并把当前项的数值和对应的index放到hashmap中
时间:O(n)
空间:O(n)
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
int n = nums.length;
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i=0;i<n;i++)
{
int cur = target-nums[i];
if(map.containsKey(cur))
{
res[0] = map.get(cur);
res[1] = i+1;
break;
}
map.put(nums[i],i+1);
}
return res;
}
}