问题描述:
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.
示例:Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
下面是问题分析:
1.对于此类问题,我们一般会想到用双层循环来实现结果的查找,这个方法在理论和实践方面都行得通。但是有一个缺陷,它的时间复杂度是O(N^2),当数据集很大时,执行效率不高。以下是运用该方法的代码示例(不推荐使用):
vector<int> twoSum(vector<int>& nums,int target){
vector<int> result;
int size = nums.size();
for(int i = 0; i < size; i++){
int temp1 = nums.at(i);
for(int j = i + 1 ; j < size; j++ ){
int temp2 = nums.at(j);
if(temp2 + temp1 == target) {
result.push_back(i);
result.push_back(j);
return result;
}
}
}
return result;
}
2.另一种比较高效的方式是使用map,用空间换时间来提高效率,此方法时间复杂度为O(N*logN)。该方法会把vector中的值nums[i]和索引i,放到map的键值对中,利用map的count方法,防止vector中重复的值的影响。以下是该方法的代码(推荐使用):
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
map<int, int> hmap;
int size = nums.size();
for(int i = 0; i < size; i++){
if(!hmap.count(nums[i])){
hmap.insert(pair<int, int>(nums[i],i));
}
if(hmap.count(target-nums[i])){
int n=hmap[target-nums[i]];
if(n<i){
result.push_back(n);
result.push_back(i);
return result;
}
}
}
return result;
}
以上就是我对本题的解答,欢迎有疑问的小伙伴来跟我探讨o~~~