您的位置:首页 > 编程语言 > C语言/C++

TwoSum c++ Map 已AC

2014-08-31 21:01 246 查看
问题描述:

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

解题思路:

刚看到这道题目时,很快用两个for语句解了出来,但AC不通过。报告runtime error,是的,它花了O(n*n);

我又尝试调用sort函数,先把数组排序,排完序后使用二分法,还是报告runtime error,二分法代码如下:

struct Node
{
int num,pos;
};

bool cmp(Node a,Node b)
{
return a.num < b.num;
}
class Solution1
{
public:
vector<int> twoSum(vector<int> &numbers, int target)
{
vector<int> result;
vector<Node>array;
int i,j,k,index1,index2;
k = sizeof(numbers)/sizeof(numbers[0]);
for(i = 0; i < k; i++)
{
Node temp;
temp.num = numbers[i];
temp.pos = i + 1;
array.push_back(temp);
}
sort(array.begin(),array.end(),cmp);
for(int i = 0, j = array.size() -1; i != j;)
{
int sum = array[i].num + array[j].num;
if(sum == target)
{
index1 = array[i].pos;
index2 = array[j].pos;
result.push_back(index1);
result.push_back(index2);
break;
}
else if(sum < target)
{
++i;
}
else
--j;

}
return result;
}
};


==============================================================

只能搜别人的方法了== 好吧,大家都直接调用Map,果然AC地过去,可是我根本不认识Map!简洁地不敢相信==都怪书读的太少==

class Solution
{
public:
vector<int> twoSum(vector<int> &numbers, int target)
{
vector<int> result;
unordered_map<int,int> num_to_pos;
for(int i = 0; i < numbers.size(); ++i)
{
int temp = target - numbers[i];
if(num_to_pos.find(temp) != num_to_pos.end())
{
result.push_back(num_to_pos[temp]);
result.push_back(i + 1);
return result;
}
else
{
num_to_pos[numbers[i]] = i + 1;
}
}
return result;
}
};


那么什么是unordered_map呢?

C++ Primer里是这么写的:

这是新标准定义的四个无序关联容器之一。这些容器不是使用比较运算符来组织元素,而是使用一个哈希函数和关键字类型的==运算符。在关键字类型的元素没有明显的顺序关系的情况下,无序容器是非常有用的。

无序容器提供了与有序容器相同的操作(find,insert,erase等)。

map和set举例

#include<iostream>
#include<map>
#include<vector>
#include<string>
#include<set>
using namespace std;

void map_test()
{
map<string,size_t> word_count;
string word;
while(cin >> word)
{
++word_count[word];
}
for(const auto &w :word_count)
{
cout<<w.first <<"  occurs  "<<w.second
<<((w.second > 1) ?"times":"time")<<endl;
}
}

void set_test()
{
map<string,size_t>word_count;
set<string> exclude;// = {"the","but","and","or","a","an","The","But","And","Or","A","An"};
exclude.insert("the");
exclude.insert("The");

string word;
while(cin>>word)
{
if(exclude.find(word) == exclude.end()) //只统计不在exclude中的单词
{
++word_count[word];
}
}
for(const auto &w :word_count)
{
cout<<w.first <<"  occurs  "<<w.second
<<((w.second > 1) ?"times":"time")<<endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: