LeetCode题库——TwoSum

Problem:

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:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].

Solution:

1、暴力解法

很容易想到用两个循环嵌套用来遍历Vector数组中的每一个元素,两两相加来和target进行比较,从而返回结果。

代码如下:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> pos;
	    int len=nums.size();
	    for (int i=0;i<len-1;i++)
    		for (int j=i+1;j<len;j++){
	    		if (nums[i]+nums[j]==target) {
    				pos.push_back(i);
    				pos.push_back(j);
    				return pos;
    			}
	    	}
    }
};

2、利用STL中的map对象

由于暴力解法的时间复杂度是O(n^2),虽然此题的测试数据较小,依然ac,但是依然要考虑时间复杂度更小的解法,因此,可以利用map这个键-值对的组合,在map对象中的find()查找的时间复杂度为o(logn),显然要比第一种方法来的效率。

代码如下:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
		vector<int> pos;
		map<int,int> map1;
		map<int,int>::iterator itr1;             //迭代器,相当于容器的指针
		int len=nums.size();
		for (int i=0;i<len;i++)	{map1.insert(pair<int,int>(nums[i],i));}
		for (int i=0;i<len;i++){
			itr1=map1.find(target-nums[i]);
			if((itr1!=map1.end())&(itr1->second!=i)){           //考虑不能重复使用元素
				pos.push_back(i);
				pos.push_back(itr1->second);
				return pos;
			}
		}
    }
};
(注意,map1.insert()函数中不用pair<int,int>可能会出问题,但是目前不知道问题的原因。)




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值