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)