您的位置:首页 > 其它

Two Sum

2014-01-27 16:39 141 查看
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 


考虑的几个点:


时间复杂度,出现重复数字,index1<index2

基本知识:
vector用法:

        头文件:#include<vector> 与其他STL组件一样,vector 属于std命名空间。

在程序不复杂的情况下可以用using namespace std;

        vector比较常用 具体可以参考: http://en.wikipedia.org/wiki/Sequence_container_%28C%2B%2B%29#Vector http://202.201.18.40:8080/mas5/bbs/showBBS.jsp?id=4943&forum=1185&noButton=yes

map用法:
头文件:#include <map> //注意,STL头文件没有扩展名.h
map对象是模板类,需要关键字key和存储对象value两个模板参数,基本构造函数: map<int , int >mapint;   

        添加数据:

    map<int ,int> maplive;
maplive[7]=6; //最简单最常用的插入方式 或者maplive.insert(pair<int,int>(7,6));

    map中元素的查找:

          寻找键值为key所在的关联对
find()函数返回一个迭代器指向键值为key的元素,如果没找到就返回指向map尾部的迭代器。        

    map<int ,string >::iterator l_it;; 

   l_it=maplive.find(7);

   if(l_it==maplive.end())

                cout<<"we do not find 7"<<endl;

  else cout<<"wo find 7"<<endl;

                

sort用法:

         sort函数中需要首尾的迭代器,当比较的对象是自己定义的类或者结构体时需要重写比较函数 

         comparesort(numnod.begin(),numnod.end(),compare); 
其中在重写compare需要类似obj : error LNK2005 fatal error LNK1169的错误,没有将compare定义为全局函数 static



方法一

//排序法O(nlog(n))
struct Num_Node
{
int val;
int ival;
};

static bool compare(const Num_Node &n1,const Num_Node &n2)
{
return n1.val<n2.val;
}

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

vector<int> ans;
//map <int,int > nummap;
Num_Node node;
vector<Num_Node> numnod;
for (int i=0;i<numbers.size();i++)
{
node.val = numbers.at(i);
node.ival = i+1;       //避免0
numnod.push_back(node);
}

sort(numnod.begin(),numnod.end(),compare);  // O(n*log(n))

int l = 0;
int r = numbers.size()-1;

while(l < r){
if (numnod.at(l).val+numnod.at(r).val==target)
{
ans.push_back(min(numnod.at(l).ival,numnod.at(r).ival));  //min避免出现index1>index2
ans.push_back(max(numnod.at(l).ival,numnod.at(r).ival));
return ans;
}
else if (numnod.at(l).val+numnod.at(r).val < target)
{
l++;
}
else
{
r--;
}
}
}
};

方法二

//关联法 O(n)
class Solution{
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> ans;
map<int,int> mapnum;
int n = numbers.size();
vector<int> numkey (n , NULL);

for (int i = 0;i<numbers.size();i++)
{
numkey[i] = (target-numbers[i])*numbers[i];

if (mapnum[numkey[i]] != NULL)
{
if (numbers[i]+numbers[mapnum.find(numkey[i])->second-1] == target)
{
ans.push_back(mapnum[numkey[i]]);
ans.push_back(i+1);
return ans;
}
}
else
mapnum[numkey[i]]  =  i+1;
}
return ans;
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: