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.可以用暴力的方法来解决,代码如下:
class Solution {
public int[] twoSum(int[] nums, int target) {
int len = nums.length;
int[] a = new int[2];
for(int i = 0 ; i < len; i++){
for(int j = i + 1; j < len ; j++){
if(nums[i] + nums[j] == target){
a[0] = i;
a[1] = j;
break;
}
}
}
return a;
}
}
时间复杂度:O(n2)
空间复杂度:O(1)
2.使用HashMap来做
class Solution {
public int[] twoSum(int[] nums, int target) {
int len = nums.length;
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int j = 0 ; j < len;j++){
int complement = target - nums[j];
if(map.containsKey(complement) && map.get(complement) < len){
return new int[]{map.get(complement),j};
}
map.put(nums[j],j);
}
throw new IllegalArgumentException("No two sum solution");
}
}
时间复杂度:O(n)
空间复杂度:O(n)