Two Sum
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].
此题可以用暴力求解,两个循环判断是否数组中存在两个数相加为目标值(不可自身与自身相加)
public int[] twoSum(int nums[], int target) {
int k = 0;
for (int i=0; i<nums.length; i++) {
for (int j=i+1; j<nums.length; j++) {
if (nums[j] == (target - nums[i])) {
return new int[] {i, j};
}
}
}
return null;
}
我们可以看到这种求法时间复杂度为O(n^2) 空间复杂度为O(1)
现在我们打算用空间换时间,改用hashmap来求解
public int[] twoSum(int nums[], int target) {
HashMap<Integer, Integer> hm = new HashMap<>();
for (int i=0; i<nums.length; i++) {
hm.put(nums[i], i);
}
for (int i=0; i<nums.length; i++) {
// cause the question needs us use different element
if (hm.containsKey(target - nums[i]) && (i != hm.get(target - nums[i]))) {
return new int[] {i, hm.get(target - nums[i]).intValue()};
}
}
return null;
}
这样时间和空间复杂度都成了O(n)
还没有评论,来说两句吧...