Most common values in an array

后端 未结 4 988
时光说笑
时光说笑 2021-01-14 22:25

How would I go about finding the three most common elements in an array? I am working with an array of length 10,000 with elements = random integer from 0-100.

I was

4条回答
  •  囚心锁ツ
    2021-01-14 23:26

        //find majority of a value in a array — O(n log n) -> wrost case O(n)
    void findMajority(){
        //sort
        sort(begin(sarray),end(sarray));
        //sarray[0] is our first number already counted
        int cont=1;
        int leader = sarray[0];
        //temp variables to know when we changed to a different number
        int tempLeader=0;
        int tempCont=0;
        //loop through sarray.size()
        for(unsigned int i=1; icont){ //its not higher occurences than our last number? skip, else we got a new leader
                    leader=tempLeader;
                    cont=tempCont;
                    tempLeader=0;
                    tempCont=0;
                }
            }
        }
        cout << "leader is" << leader << endl;
    }
    

    sorry, its a crappy solution, but it works like you asked, hope it helps

提交回复
热议问题