查找整数序列中没有对的整数

To find a integer without a pair in a sequence of integers

本文关键字:整数 查找      更新时间:2023-10-16

问题是在整数序列中找到一个没有成对的整数。这是我到目前为止写的,对我来说,它看起来应该有效,但它没有。对菜鸟程序员有什么帮助吗?

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. 传入的向量不为空,
  2. 找到的第一个计数为 1 的项目是孤独值。
  3. 至少有一个"孤独的价值"。

我还更改了签名以通过引用获取向量而不发送计数(因为向量知道自己的大小(。

该代码不执行任何手动编码的循环,因此这是删除的错误源之一。

其次,一个数字被看到的次数的计数或多或少,由地图使用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 的条目,并将其存储在将返回的向量中。

简单的答案可能是对列表进行排序,然后查找前后具有不同值的内容。

您的问题是列表中任何给定值的最后一项没有后续重复值,并且您认为没有后续重复项与没有重复项(这是错误的(相同。

如果您不想删除您的内部外观已经看到的值,并且之前将其标识为内部循环中所有值的"上一个"值循环的副本,则忽略与自身的匹配。