Two Sum

原题链接:http://oj.leetcode.com/problems/two-sum/

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        
    }
};

解决思路:

1.最简单,进行2重遍历,对任意一对数字进行相加看是否满足target值,若满足返回下标。运行时间为N*N,太慢。

2.假设这一串数字中V1+V2=TARGET,且V1在V2之前,则我们可以想象,如果我们没遇到一个数,就保存期与target的差值,则在遇到一个前面已存在的差值相等的新数字,则满足。如在遇到V1时保存TARGET-V1的值为V2,在真正遇到V2时,我们发现正是需要的。

采用map<int ,int>,key为每次计算的差值,value为其下标。

新来一个数字,查看是否map中存在与其相等的值,若存在,则满足。若不存在,计算与target差值,并保存在map中。

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        map<int, int> value_index;
        for(vector<int>::size_type i = 0; i<numbers.size(); i++){
        	int number = numbers[i];
        	map<int, int>::iterator it = value_index.find(number);
        	if(it==value_index.end()){
        		value_index.insert(map<int, int>::value_type(target-number, i+1));
        	}
        	else{
        		int index1 = i+1;
        		int index2 = it->second;
				numbers.clear();
				numbers.push_back(index2);
				numbers.push_back(index1);
				return numbers; 
        	}
        }
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值