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].
解决方法:
①暴力破解,第一层循环给定一个数nums[i],第二层循环查找符合nums[j] == target - nums[i]的值,从第i+1个数开始查找。思路最简单,用时48ms
public 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 ++ ) {
if (nums[j] == target - nums[i]) {//使用条件nums[j]+nums[i]==target也可以
return new int[]{i,j};//注意返回数组的方式
}
}
}
return null;//因为题目给定的情景不会出现这种情况,所以随意返回
}
}
时间复杂度:O(n^2)因为要双重循环遍历值,空间复杂度:O(1)
②双向hash表,比较快速的方法是使用HashMap来存放数值及其下标,然后使用map的方法来查找另一个值。用时11ms
public class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for (int i =0;i < nums.length ;i ++ ) {
map.put(nums[i],i);
}
for (int i =0;i < nums.length ;i ++ ) {
int sub = target - nums[i];
if(map.containsKey(sub) && map.get(sub) != i){//注意map方法及其返回值。
return new int[]{i,map.get(sub)};
}
}
return null;
}
}
时间复杂度:O(n),因为使用了hash方法查找第二个值。空间复杂度:O(n),新建了hash map。