题目链接:https://leetcode.com/problems/majority-element/
题目描述:
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.
这是一道很常见的题了,就是找到一组数据中的多数元素(即出现次数一半以上)。
因为大学的时候老师讲过这道题,一直有印象,所以直接上思路。
因为这个数出现次数大于一半,所以,给这个数组里的数配对,不相同的相互抵消,最后剩下的肯定是那个majority element。
这里用value保存当前用来比较的值,计数器count保存比较的结果;
1.在下次比较前,先对count做判断,如果count == 0,则将待比较的值赋给value,同时count加1;
2.如果count != 0,进行比较,如果不相同count减1,相同count加1;
3.将最后的value值返回
代码如下:
int majorityElement(int num[], int n) {
int count = 0;
int value;
for(int i = 0; i < n; i++){
if(count == 0){
value = num[i];
count++;
}else{
if(value == num[i]){
count++;
}else{
count--;
}
}
}
return value;
}
难的是在网上搜到另外一个算法,觉得很好,如下:(http://blog.163.com/xie_wenbin613/blog/static/175489095201242625851399/)
分析:
如果一个数字才数组中出现的次数超过了数组长度的一半,那么对这个数组进行排序,位于数组中间位置的那个数就是出现次数超过一半的那个数。对数组排序的时间复杂度是O(nlog(n)),但是对于这道题目,还有更好的算法,能够在时间复杂度O(n)内求出。我们写过快速排序算法,其中的Partition()方法是一个最重要的方法,该方法返回一个index,能够保证index位置的数是已排序完成的,在index左边的数都比index所在的数小,在index右边的数都比index所在的数大。那么本题就可以利用这样的思路来解。
- 通过Partition()返回index,如果index==mid,那么就表明找到了数组的中位数;如果index<mid,表明中位数在[index+1,end]之间;如果index>mid,表明中位数在[start,index-1]之间。知道最后求得index==mid循环结束。
- 根据求得的index,遍历一遍数组,每当出现一个等于index所指向的数时time++,最后判断time是否大于数组长度的一半,如果大于则表明index所指向的数就是所求的数,如果不是,则表明不存在一个数出现的次数超过数组长度的一半。