Act One: violence to solve
- time complexity:
- Space complexity:
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;
}
}
Dish to syncope ...
Act II: twice a hash table
- time complexity:
- Space complexity:
- Trade space for speed
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");
}
}
- At first glance this code, you might think to find an element in the hash table is not it, this is precisely the point. Hash table uses amappingrelationship (mapping function), which makesno conflictin the case where the time complexity is ,, .
Act III: hash table again
- time complexity:
- Space complexity:
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");
}
}