法一:暴力求解
- 时间复杂度: O ( n 2 ) O(n^2) O(n2)
- 空间复杂度: O ( 1 ) O(1) O(1)
class Solution {
public int[] twoSum(int[] nums, int target) {
int i,j;
int[] result = new int[2];
for(i=0;i<nums.length-1;i++){
for(j=i+1;j<nums.length;j++){
if(nums[i]+nums[j]==target){
result[0] = i;
result[1] = j;
return result;
}
}
}
return result;
}
}
菜到晕厥…
法二:两遍哈希表
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( n ) O(n) O(n)
- 以空间换取速度
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
- 初看这段代码,你可能会以为在哈希表中查找元素不也是 O ( n ) O(n) O(n)吗,这恰恰是问题的关键。哈希表采用的是映射的关系(映射函数),这使得在没有冲突的情况下,,时间复杂度就是 O ( 1 ) O(1) O(1)。
法三:一遍哈希表
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( n ) O(n) O(n)
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<>();
for(int i=0;i<nums.length;i++) {
int complement = target-nums[i];
if(map.containsKey(complement)&&map.get(complement)!=i) {
return new int[] {i,map.get(complement)};
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No such two sum solution");
}
}