Programming beauty 2.3--Looking for the Navy (offset method)

Source: Internet
Author: User

1. Look for an element in the array that has more than half occurrences.

2. Look for three elements with more than 1/4 occurrences in the array.

Ideas

1) General Practice: First sorting the array, Time O (Nlogn), and then traversing once, counting the number of occurrences of each element, to get the title request.

2) The practice of Time O (n): the offsetting method. For the first question, each time you cancel two different numbers, the number of main elements remaining in the array is more than half. That is, the idea of narrowing the scale of the problem.

For the second problem, the 4-digit offset is converted to a smaller size.

The code to counteract two numbers is simple:

intFindoverhalf (int*id,intN) {    intntimes=0; intCandi;  for(intI=0; i<n; i++){        if(ntimes==0) {Candi=Id[i]; Ntimes=1; }        Else{            if(candi==Id[i]) ntimes++; ElseNtimes--; }    }    returnCandi;}

Offsetting four numbers is more troublesome and difficult to write comprehensively:

"Other Code"

structcandidate{intA,atimes; intB,btimes; intC,ctimes; voidinit () {atimes=0; Btimes=0; Ctimes=0; }    BOOLIsthesame (intnum) {        if(a==num&&atimes!=0) {atimes++;return false;} if(b==num&&btimes!=0) {btimes++;return false;} if(c==num&&ctimes!=0) {ctimes++;return false;} if(atimes==0) {a=num;atimes++;return false;} if(btimes==0) {b=num;btimes++;return false;} if(ctimes==0) {c=num;ctimes++;return false;} return true; }    voiddel () {atimes--; Btimes--; Ctimes--; }}person;candidate Findoverquarters (int*id,intN)    {Person.init ();  for(intI=0; i<n; i++){        if(Person.isthesame (Id[i])) Person.del (); }    returnPerson ;}intMain () {intid[]={1,1,2,2,2,3,3,3,4,4,4}; person=findoverquarters (ID, One); cout<<person.a<<person.b<<person.c<<Endl; System ("Pause"); return 0;}

The test run code is 4,2,3.

Summary

To learn how to encapsulate the code of others.

Programming beauty 2.3--Looking for the Navy (offset method)

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.