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].
问题描述:
在给定的一个数组中超出两个数字,让这个两个数字之和等于一个给定的值。假设数组中至少存在一组满足要求。
解题思路:
1.穷举法 暴力求解
遍历所有的两个数之和,直到找到等于目标值的两个数即可。该方法的时间复杂度为O(n²)
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法 以空间换时间 O(N)
用hash表去存储目标值和其中一个数字之差在数组中的位置
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;
}