//waterking.cpp: Defines the entry point of the console application. //#include"stdafx.h"#include"iostream"using namespacestd;voidData (intLengthinta[]) {cout<<"Please enter a list of IDs:"<<Endl; for(intI=0; i<length;i++) {cin>>A[i]; }}intMain () {intlength; intsingle=0; intID;//set the semaphorecout<<"Please enter the number of posts:"; CIN>>length; int* waterking=New int[length]; Data (length,waterking); for(intI=0; i<length;i++) { if(single==0) {ID=Waterking[i]; Single++; } Else if(waterking[i]==ID) { single++; } Else{ Single--; }} cout<<"Water King Absalom:"<<ID<<Endl; return 0;}
Iv. Results of the experiment
V. Analysis of results
This is a very typical requirement algorithm optimization, code is not long, mainly to consider what method should be implemented, how to achieve the optimization of the code. To achieve the optimization of the code, the first thing to solve is to find the core of the problem, from the core, in order to have ideas to explore ways to solve the problem. In this problem, according to the conditions we can know, more than half of the posts are an ID, so, as long as the median value, you can find the so-called Water King, but, this optimization is not perfect, to reduce his time complexity to O (n^2), you need to consider the same ID and the relationship between different IDs, for different IDs , direct exclusion, then you can rule out the existence of water King, because the water king Post number is large enough, then the last remaining must be the water king.
In this problem, the code optimization process is not an overnight, but a gradual thinking in depth, to find the key point of the problem to gradually achieve the ideal optimization process. And this process is exactly what we need to focus on.