If a number is known to occur more than half times, use an O (n) complexity algorithm to find the number.

Source: Internet
Author: User

Now that there is an array that is known to be more than half the number of occurrences, use an O (n) complexity algorithm to find this number.

Analysis: Set number A appears more than half times. Each time you delete two different numbers, the number a appears more than half in the remaining number. By repeating this process, the final result is obtained. This topic is the same as the beauty of programming in the search for water kings.

[CPP]  View plain copy #include <iostream>   using namespace std;  //size the size of array a   //Returns more than half of the numbers in the array    int search (int *a,int size)    {       int count=0;       int current;       for (int i=0;i<size;i++)        {            if (count==0)             {               current=A[i];                count=1;              }            else           {   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBsp;      if (a[i]==current)                     count++;                else                    count--;            }             }       return  current;  }   int main ()    {       int  A[6]={1,2,2,1,1,1};       int B[7]={1,0,1,0,0,1,1};        int C[7]={3,4,6,3,3,3,7};       cout<<search (a,6) << " ";       cout<<search (b,7) << " ";     &nbSp; cout<<search (c,7) << " " <<endl;       int i;        cin>>i;       return 0;   }  


[CPP] view plain copy

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.