Personal information: enrolled in the University of Yan undergraduate software project Major in the current three;
Personal Hobbies: Love data structure and algorithms, hope to work in the future algorithm to make their own contribution to the people;
Mathematical modeling: There are a bunch of people posting, each person posting a ID identification, and then find out the half of the post ID. (if there is already more than half of this post ID)
Each is identified by an int whose ID is like an element of an array, trying to find the number of more than half the ID.
Method: Offset method
Since there is an ID number of more than half, then it is the most, but it can be used to offset the other ID number, one-to-one to cancel, the last of the most will remain a lot, this time we know the answer
Personal algorithm design such as the following (time complexity O (n), n array length)
static int _find_more_than_half (int[] data) {int result = data[0] ; int number = 1;for (int i = 1;i < data.length;i++) {if (result = = Data[i]) number++;else{number--;if (number = = 0) {result = data [i];}}} return result;}
This algorithm has a flaw, that is, if there is no more than half the ID of the post, it will find the wrong answer; Assuming that there is a half-post ID, it will give the correct answer.
For eg: arrays
int[] Data ={ 1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2 , 2,4,4,44,4};
It will give 2 (right now)
For eg: arrays
int[] Data ={1,1,2,2};
He will give 2 (which is wrong at this time)
So we need to strictly check whether the given data conforms to the problem model and then make the choice.
This time the problem has turned into an element that checks whether an array has more than half the number.
The answer is given in the next article, thank you