描述
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].思路
先使用for循环确定当前数字,再嵌套一个for循环匹配第二个数字,一旦满足要求,就进行返回。
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] out = new int[2];
for(int i =0;i<nums.length;i++){
boolean flag = false;
for(int j =i+1;j<nums.length;j++){
if(nums[i] + nums[j] == target){
out[0] = i;
out[1] = j;
flag = true;
break;
}
}
if(flag){
break;
}
}
return out;
}
}可以暴力AC,但是时间复杂度和空间复杂度都不是很好。
Runtime: 59 ms, faster than 18.99% of Java online submissions for Two Sum.
Memory Usage: 39.3 MB, less than 6.43% of Java online submissions for Two Sum.
优化
看到问题讨论区有使用map作为辅助查询工具的,可以大大提高数据检索速度。
public int[] twoSum(int[] numbers, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < numbers.length; i++) {
if (map.containsKey(target - numbers[i])) {
result[1] = i;
result[0] = map.get(target - numbers[i]);
return result;
}
map.put(numbers[i], i);
}
return result;
}该算法的思路是:使用for循环进行遍历,当前数据为i所记录的位置,但是不同的是它进行前向查找,将当前数据和之前已经完成遍历的数据匹配。这样做的好处在于可以将已遍历过的数据加入map集合,方便进行比对、节约检索时间和回退时间,且不会出现二次匹配成功的问题。
Runtime: 1 ms, faster than 99.90% of Java online submissions for Two Sum.
Memory Usage: 42.4 MB, less than 5.65% of Java online submissions for Two Sum.
可以看到时间复杂度大幅提高,空间开支增加。