Find out more than half the number of occurrences in an array (i)

Source: Internet
Author: User

The teacher left this Microsoft face question and gave the idea

J is used to temporarily store the data in an array, and count is used to store the number of occurrences.
At the beginning, K stores the first number in the array, count is 0, if the array appears in the number of J equals, then J plus 1, or minus 1, if J is 0, the number in the current array is assigned to J
Because the specified number of occurrences is greater than half the length of the array, after all count++ and count--are offset, the last count value is greater than or equal to 1, and the number that is present in J is the number that appears most.

#include <iostream>using namespacestd;intSearchintA[],intsize) {    if(NULL = = A | | size<=0)    {        return-1; }    intCount =0; intJ;  for(inti =0; i<size; i++)    {        if(Count = =0) {J=A[i]; Count=1; }        Else        {            if(A[i] = =j) Count++; ElseCount--; }    }    returnJ;}intMain () {inta[6] = {1,2,2,5,5,5 }; cout<< Search (A,6) <<" "; return 0;}

Find out more than half the number of occurrences in an array (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.