Two Sum
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==
Ignored Points
- To save time, I try to sort the array first. But this question requires to return indices as the output. If sorted, the indices will be changed.
- create a new int with values: new int[]{i, j}
Solution 1: time complexity: O(n^2) space: O(1)
class Solution {
public int[] twoSum(int[] nums, int target) {
if(nums == null || nums.length < 2)
return null;
for(int i = 0; i < nums.length-1; i++) {
for(int j = i+1; j < nums.length; j++) {
if(nums[i]+nums[j] == target)
return new int[]{i, j};
}
}
return null;
}
}
Solution 2: time complexity: O(n^2) space: O(1)
Improved: if the number is the same as previous one, no need to repeat the comparison
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i = 0; i < nums.length-1; i++) {
if(i>0 && nums[i]==nums[i-1])
continue;
for(int j = i+1; j < nums.length; j++) {
if(nums[i]+nums[j] == target)
return new int[]{i, j};
}
}
return null;
}
}
Solution 3: use hash map, time complexity: O(n) space: O(n)
Noted: hashmap functions for containsKey, get
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
int[] result = new int[2];
for(int i = 0; i < nums.length; i++) {
if(map.containsKey(target-nums[i])) {
result[0] = map.get(target-nums[i]);
result[1] = i;
return result;
}
map.put(nums[i],i);
}
return result;
}
}