Its actually the following assumption in the question : You may assume that the array is non-empty and the majority element always exist in the array actually which makes the input wrong, bcoz otherwise, we would need to make sure that the element num[majorityIndex] would be > n/2 .
@gangan Since you have changed your original solution to Boyer-Moore, you should also change your original description too. Besides, your original solution doesn't work.
For ⌊n/k⌋ cases, it is not guaranteed that there will be more than or equal to k different elements. And there can be more than 1 remaining elements that do not have counterpart to remove.
It's Boyer-Moore majority vote algorithm,you can refer to this link http://www.cs.rug.nl/~wim/pub/whh348.pdf .
Accroding to the problem description, we have known that the majority element always exist in the array,so the first iteration will get the result.
'res' actually represents potential majority element in the array. In general, one more pass is required to confirm if 'res' is actually majority element or not. However since in this problem we are told that majority element always exists, we can safely assume 'res' represents majority element.
In cases where there is no majority element in the array, 'res' would just point to random element in array.
This solution is based on algorithm called Moore's Voting algorithm.