这道题比较简单,用了Map对key值查找的常数时间的特性, 使得该算法的时间复杂度为O(n)。
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> numCache = new HashMap<Integer, Integer>();
for(int i = 0; i < nums.length; i++)
{
if(numCache.containsKey(target - nums[i]))
{
int index = numCache.get(target - nums[i]);
int[] result = {index, i};
return result;
}
numCache.put(nums[i], i);
}
return null;
}
}