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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
给定一个整数数组和一个目标数target,返回和恰好等于target的两个元素的序号,这里假定每个输入都有恰好唯一解。
思路
这类问题基本的思路是要顺序扫描数组,对于当前元素nums[i],扫描数组中是否存在元素target-nums[i],主要通过两种方式查找:
- 排序数组,二分查找,但此题目需要返回解元素的序号,因而此种方式不适用
- 构建一个哈希map,用于保存数组元素以及它们的序号,此方法遍历时间O(n),寻找时间O(1),总时间复杂度O(n),空间复杂度O(n)。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> hash;
vector<int> result;
for(int i=0;i!=nums.size();i++){
int numsToFind = target-nums[i];
if(hash.find(numsToFind)!=hash.end()){
result.push_back(hash[numsToFind]);
result.push_back(i);
return result;
}
hash[nums[i]]=i;
}
return result;
}
};
public class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map=new HashMap<>();
for(int i=0;i<nums.length;i++){
int numToFind=target-nums[i];
if(map.containsKey(numToFind)) return new int[]{ map.get(numToFind),i};
map.put(nums[i],i);
}
throw new IllegalArgumentException("No two sum solution");
}
}
网友评论