向量 - 首先出现 k 次的值

Vector - value with k-occurences first

这是我的第一个 post 希望我没有做错任何事。 我正在尝试编写一个程序来找到向量中出现 k 次的第一个值。

例如,给定此向量且 k=3:

1 1 2 3 4 4 2 2 1 3

我会看到 2 作为输出,因为 2 是第一个出现第 3 次的数字。

下面的代码是我试过的运行,但不知何故输出不正确。


    #include<iostream>
    #include<vector>

    using namespace std;

    int main()
    {

        vector<int> vettore;
        int k;
        int a,b,i;
        int occ_a;
        int occ_b;

        cout<< "Write values of vector (number 0 ends the input of values)\n"; 
        int ins;
        cin>>ins;
        while(ins)
        {
            vettore.push_back(ins);     //Elements insertion
            cin>>ins;
        }
        cout<<"how many occurrences?\n"<<endl;;
        cin>>k;
        if(k>0)
        {
            int i=0;
            b = vettore[0];
            occ_b=0;

            while(i< vettore.size())
            {

                    int j=i;
                    occ_a = 0;
                    a = vettore[i];
                    while(occ_a < k && j<vettore.size())
                    {
                        if(vettore[j]== a)
                        {
                            occ_a++;
                            vettore.erase(vettore.begin() + j);
                        }
                        else
                            j++;
                    }
                    if(b!=a && occ_b < occ_a)
                        b = a;
                    i++;

            }
            cout << b;   //b is the value that reached k-occurrences first
        }
        return 0;
    }

几个小时过去了,我还是没能解决。

感谢您的帮助!

您的代码难以阅读,因为您在不使用变量的地方声明了变量。所以他们的意思很难理解。

也不需要从向量中移除元素。找到第一个出现 k 次的值并不等同于更改向量。它们是两个不同的任务。

我可以建议以下演示程序中所示的解决方案。

#include <iostream>
#include <vector>

int main() 
{
    std::vector<int> v = { 1, 1, 2, 3, 4, 4, 2, 2, 1, 3 };
    size_t least_last = v.size();
    size_t k = 3;

    for ( size_t i = 0; i + k <= least_last; i++ )
    {
        size_t count = 1;
        size_t j = i;

        while ( count < k && ++j < least_last )
        {
            if ( v[j] == v[i] ) ++count;
        }

        if ( count == k ) 
        {
            least_last = j;
        }           
    }

    if ( least_last != v.size() ) std::cout << v[least_last] << '\n';

    return 0;
}.

程序输出为

2

思路是找到出现k次的第一个元素的最后位置。一旦找到,遍历序列的上限就设置为这个值。因此,如果有另一个元素在此限制之前出现 k 次,则意味着与已找到的元素相比,它首先出现。