Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Solution:
1. Brute Force
a. 这是我第一反应的解法,常规的循环遍历相加
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] ans = new int[2];
for (int i = 0; i <= nums.length - 2; ++i) {
for (int j = i + 1; j <= nums.length - 1; ++j) {
if (nums[i] + nums[j] == target) {
ans[0] = i;
ans[1] = j;
return ans;
}
}
}
throw new IllegalArgumentException("no match found");
}
}
b. 这种暴力搜索方法是做减法,更容易引申下面HashMap的解法
class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; ++i) {
for (int j = i + 1; j < nums.length; ++j) {
int complement = target - nums[i];
if (nums[j] == complement) {
return new int[] {i, j};
}
}
}
throw new IllegalArgumentException("no match found");
}
}
2. HashMap
HashMap存储nums数组的值和角标的键值对,找到则返回,找不到则存入HashMap
此种解法时间复杂度为O(n)
注意,HashMap containsKey方法的时间复杂度为O(1),containsValue方法的时间复杂度为O(n)
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; ++i) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[]{map.get(complement), i};
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("no match found");
}
}