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.

示例:

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~~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值