Domanda

I have to find the major element of the sequence :

92,19,19,76,19,21,19,85,19,19,19,94,19,19,22,67,83,19,19,54,59,1,19,19

A major element is the one which appears more that size/2 times in the collection.

now the problem is that after counting 92 it will remove all the elements from the collection with value 92 and after that it will count the number of 19s.The number of 19′s in this sequence is 13 but the count algorithm is just returning 1. The count algorithm is returning the proper answer for just the first element of the sequence.

Here’s the function:

int countMajor(vector<int>& v)
{
  int max = (v.size() / 2);
  int c = 0;
  do{
    c = count(v.begin(), v.end(), v[0]);
    if (c > max)
      return v[0];
    v.erase(remove_if(v.begin(), v.end(), [&v](int i){
      if (v[0] == i)
        return true;
      return false;
    }), v.end());
  } while (!v.empty());
  return -1;
}

After counting 92 it will be removed and v[1] i.e 19 will be the new v[0]. I am unable to figure out what am I doing wrong.

È stato utile?

Soluzione

You are erasing v[0].

Make it:

int e = v[0];
v.erase(remove_if(v.begin(), v.end(), [e](int i){
  if (e == i)
    return true;
  return false;
}), v.end());
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top