No4.Week 4

1.Description

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

2.How to deal with

Method 1: 

Sort all the elements in the vector and the middle one is the solution because the majority element appears more than ⌊ n/2 ⌋ times.However I met th
e time limit exceeded. For what?


Method 2:

Apply the Voting algorithm to solve the problem.


everytime the count == 0 (assume that at this time the element whose count equals to 0 happened to appear a times) means that in the former part of the array which length is 2a, there is an element which appears a times. And at this time we divid the original problem into two parts such that the size of the problem is cut down and at the same time it means that if the element is the majority element, then it must appears more than  ⌊ n-a/2 ⌋  . If the next time the element 's count equals to 0 and this element doesn't equal to the former element whose count ==0, it still work because it means that this element must appears less than half the time in the former part of the array and if it can be the majority element, it must appears more than half the left part of the array.Thus there exits two final situations. One is that when it goes to the last elementof the array, the count == 0,then the result is the final element of the array. Another situation is that the count still > 0 when it goes to the last element of the array, then the result is the element whose count is still > 0.

猜你喜欢

转载自blog.csdn.net/its_noah/article/details/62236717
今日推荐