Two Sum

来源:互联网 发布:删除文件 linux 编辑:程序博客网 时间:2024/04/29 10:20

原题链接: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;         }        }    }};


0 0
原创粉丝点击