1 Two Sum
- Two Sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6 Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6 Output: [0,1]
Constraints:
2 <= nums.length <= 104 -109 <= nums[i] <= 109 -109 <= target <= 109 Only one valid answer exists.
Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?
如果无视每个元素只能访问2次的规则,写时间复杂度 O(n2) 的代码很简单,双层循环即可:
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] ret=new int[2];
outter:for(int i=0;i<nums.length-1;++i){
for(int j=i+1;j<nums.length;++j){
if(nums[i]+nums[j]==target){
ret[0]=i;
ret[1]=j;
break outter;
}
}
}
return ret;
}
}
接下来是 O(n) 的方法,建一个 HashMap 。先遍历一遍,储存每个元素的和 target 的差值和下标(键是每个元素与 target 的差,值是下标)。在遍历一遍,如果一个元素值和某个元素与 target 的差相等,且下标与那个元素不一样,则说明是要找的元素。
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map=new HashMap<>();
int t;
int[] ret=new int[2];
for(int i=0;i<nums.length;++i){
map.put(target-nums[i],i);
}
for(int i=0;i<nums.length;++i){
t=nums[i];
if(map.containsKey(t) && map.get(t)!=i){
ret[0] = i;
ret[1] = map.get(t);
break;
}
}
return ret;
}
}
不过还不是最优解,其实可以只遍历一次,每次插入 map 前检查 map 是否有元素与之和为 target
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map=new HashMap<>();
int[] ret=new int[2];
for(int i=0;i<nums.length;++i){
if(map.containsKey(nums[i])){
ret[0]=i;
ret[1]=map.get(nums[i]);
break;
}
map.put(target-nums[i],i);
}
return ret;
}
}