Looking for a post water king This topic gave me a lot of inspiration, while broadening the vision, often in solving this type of problem when the first idea is to sort and then calculate. But the subject has given a very good idea, the time complexity of O (N).
It also has an extension problem, but I read on the Internet a few of the poorly considered, some write the logic is not very clear, here I also based on thinking and review, give my own solution.
typedef intType;//Give an abstract of the IDType candidate[3] = {0};//Description to initialize before this parameter is passed. voidFind3 (type* ID,intn,type* candidate) {intIintntimes[3] = {0}; for(i=0; i<n;i++) {if(ntimes[0] ==0){if(candidate[1] = = Id[i]) {ntimes[1]++;Continue; }Else if(candidate[2] = = Id[i]) {ntimes[2]++;Continue; } candidate[0] = Id[i]; }Else if(ntimes[1] ==0){if(candidate[0] = = Id[i]) {ntimes[0]++;Continue; }Else if(candidate[2] = = Id[i]) {ntimes[2]++;Continue; } candidate[1] = Id[i]; }Else if(ntimes[2] ==0){if(candidate[0] = = Id[i]) {ntimes[0]++;Continue; }Else if(candidate[1] = = Id[i]) {ntimes[1]++;Continue; } candidate[2] = Id[i]; }Else if(candidate[0] = = Id[i]) ntimes[0]++;Else if(candidate[1] = = Id[i]) ntimes[1]++;Else if(candidate[2] = = Id[i]) ntimes[2]++;Else{ntimes[0]--; ntimes[1]--; ntimes[2]--; } }}
Here I take the parameter as the result of the return value, on the one hand because many times the following situation occurs:
Type* find3(Type* ID,int N){ //... int candidate[3] = {0}; //... return candidate;}
This way the function exits without the result, and candidate points to an unknown area of the stack.
Or
type* Find3 (type* id,int N) {
...
int* candidate = new Int[3];
...
return candidate;
}
New in the Find3, but where to release it. I still prefer where new is and where to delete.
Finally, in judging ntimes[0] = = 0 when also to judge Id[i] and other candidate is equal, so I asked candidate to initialize first.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
The charm of numbers--looking for a post water king