问题是找到一个整数序列中没有它的整数。这是我到目前为止所写的内容,对我来说它看起来应该有效,但它并没有。对noob程序员有什么帮助吗?
using namespace std;
int lonelyinteger(vector < int > a, int _a_size) {
for (int i = 0; i < _a_size; i++)
{
bool flag = false;
for (int n = i + 1; n < _a_size; n++)
{
if (a.at(i) == a.at(n))
{
flag = true;
break;
}
}
if (flag == false)
{
return a.at(i);
}
}
return 0;
}
对于输入1 1 2
,它输出1
,而它应该2
对于0 0 1 2 1
,它会输出0
,此处必须为2
答案 0 :(得分:1)
问题是你的内部循环只从索引i
开始检查并继续复制。在1 1 2
的情况下,第一个循环遇到a[1]
1
。在该索引之后,没有等于1
的元素,因此该函数返回1
。
一般来说,这个问题有一个更好的解决方案。您可以使用一个集来跟踪已经遇到的所有元素,而不是通过向量两次。对于每个元素,检查集合是否已包含它。如果没有,请将其添加到集合中。否则,将其从集中删除。集合中剩余的任何内容在向量中都是唯一的。
答案 1 :(得分:1)
所有答案都很好。
现在,假设数组不能进行排序,这是使用std::map
的一种有点懒惰的方法,但显示了使用各种算法函数可以做什么。
#include <map>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int lonelyinteger(const std::vector<int>& a)
{
typedef std::map<int, int> IntMap;
IntMap theMap;
// build the map
for_each(a.begin(), a.end(), [&](int n){ theMap[n]++; });
// find the first entry with a count of 1
return
find_if(theMap.begin(), theMap.end(),
[](const IntMap::value_type& pr){return pr.second == 1; })->first;
}
int main()
{
std::vector<int> TestVect = { 1, 1, 2 };
cout << lonelyinteger(TestVect);
}
此代码假设
1
计数的第一项是孤独的价值。 我还将签名更改为通过引用获取向量而不发送计数(因为向量知道自己的大小)。
代码不执行任何手动编码循环,因此删除了一个错误源。
其次,看到一个数字的次数的次数或多或少,由地图使用operator[]
插入新条目,++
来增加条目的计数。
最后,只使用std::find_if
搜索第一个只有1的条目,再次保证成功(假设数据遵循上述假设)。
所以基本上,如果没有真正努力,可以使用算法函数和std::map
关联容器的使用来编写解决方案。
如果您的数据包含多个(甚至没有)&#34;孤独&#34;整数,可以进行以下更改:
#include <map>
#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
std::vector<int> lonelyinteger(const std::vector<int>& a)
{
std::vector<int> retValue;
typedef std::map<int, int> IntMap;
IntMap theMap;
// build the map
for_each(a.begin(), a.end(), [&](int n){ theMap[n]++; });
// find all entries with a count of 1
for_each(theMap.begin(), theMap.end(),
[&](const IntMap::value_type& pr)
{if (pr.second == 1) retValue.push_back(pr.first); });
// return our answer
return retValue;
}
int main()
{
std::vector<int> TestVect = { 1, 1, 2, 3, 5, 0, 2, 8 };
std::vector<int> ans = lonelyinteger(TestVect);
copy(ans.begin(), ans.end(), ostream_iterator<int>(cout," "));
}
请注意,我们现在检索项目为1的任何条目,并将其存储在将要返回的向量中。
答案 2 :(得分:0)
简单的答案可能只是对列表进行排序,然后寻找在它之前和之后具有不同值的内容。
您的问题是列表中任何给定值的最后一项没有后续重复值,并且您认为没有后续重复项与没有重复项相同(这是错误的)。
如果您不想删除内部外观所看到的值,并且之前已将其标识为&#34;之前的&#34; value循环遍历内部循环中的所有值,忽略与自身的匹配。