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].
問(wèn)題描述:
在給定的一個(gè)數(shù)組中超出兩個(gè)數(shù)字,讓這個(gè)兩個(gè)數(shù)字之和等于一個(gè)給定的值。假設(shè)數(shù)組中至少存在一組滿足要求。
解題思路:
1.窮舉法 暴力求解
遍歷所有的兩個(gè)數(shù)之和,直到找到等于目標(biāo)值的兩個(gè)數(shù)即可。該方法的時(shí)間復(fù)雜度為O(n2)
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
if (nums == null || nums.length < 2) return result;
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
result[0] = i;
result[1] = j;
break;
}
}
}
return result;
}
2.hash法 以空間換時(shí)間 O(N)
用hash表去存儲(chǔ)目標(biāo)值和其中一個(gè)數(shù)字之差在數(shù)組中的位置
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
if (nums == null || nums.length < 2) return result;
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i])) {
result[0] = map.get(nums[i]);
result[1] = i;
} else {
map.put(target - nums[i], i);
}
}
return result;
}