查找整数序列中没有对的整数
To find a integer without a pair in a sequence of integers
问题是在整数序列中找到一个没有成对的整数。这是我到目前为止写的,对我来说,它看起来应该有效,但它没有。对菜鸟程序员有什么帮助吗?
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
问题是您的内部循环只从索引i
开始检查重复项。在1 1 2
的情况下,第一个循环遇到a[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);
}
现场示例:http://ideone.com/0t89Ni
此代码假定
- 传入的向量不为空,
- 找到的第一个计数为
1
的项目是孤独值。 - 至少有一个"孤独的价值"。
我还更改了签名以通过引用获取向量而不发送计数(因为向量知道自己的大小(。
该代码不执行任何手动编码的循环,因此这是删除的错误源之一。
其次,一个数字被看到的次数的计数或多或少,由地图使用operator[]
插入新条目,++
增加条目上的计数来完成。
最后,搜索计数仅为 1 的第一个条目是用 std::find_if
完成的,再次保证成功(假设数据遵循上述假设(。
所以基本上,不用真正努力,就可以使用算法函数和std::map
关联容器的使用来编写解决方案。
如果数据将由多个(甚至没有("孤独"整数组成,则可以进行以下更改:
#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," "));
}
现场示例:http://ideone.com/40NY4k
请注意,我们现在检索任何项为 1 的条目,并将其存储在将返回的向量中。
简单的答案可能是对列表进行排序,然后查找前后具有不同值的内容。
您的问题是列表中任何给定值的最后一项没有后续重复值,并且您认为没有后续重复项与没有重复项(这是错误的(相同。
如果您不想删除您的内部外观已经看到的值,并且之前将其标识为内部循环中所有值的"上一个"值循环的副本,则忽略与自身的匹配。
- 查找存储在二叉搜索树的所有非叶子中的数据总和?(返回整数的独立递归函数
- 查找多个向量之间的公共元素(无整数元素)
- 查找满足浮点不等式方程的最小整数
- 递归函数,用于查找 2 个整数之间的最大值
- 在大整数数组中查找子数组
- 查找整数数组中最接近的数字
- C++ 将二进制字符串转换为整数或比较 2 个字符串以查找差异数
- 移位运算符如何在查找两个整数中的不同位数?
- 查找多维数组中整数的出现次数(以C++为单位)
- 在非负整数的未排序数组中查找第 k 个最小元素
- 如何使用字符串流查找字符串中的整数总和?
- 如何在给定任意数量的整数的情况下创建一个唯一键?并使用该键存储,然后从地图中查找
- C++ 在数组中查找整数
- 函数中查找整数部首的意外行为/错误
- 如何使用字符串::与整数查找?C
- 查找整数中的重复模式
- 如何查找具有一组整数的函数的'max absolute sum'
- 查找序列中最大和最小的 2 个整数
- 在C++中使用 for 循环从用户输入中查找最大和最小整数
- 按 3 整数查找值的有效方法