原题链接:https://leetcode.com/problems/majority-element/
1. 题目介绍
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.
给出一个长度为 n 的数组。找出其中的“主要元素”。什么样的元素是“主要元素”呢?在数组中出现次数大于 ⌊ n/2 ⌋ 次的元素就是“主要元素”。这里 n/2 是向下取整的。
你可以假设给出的都是非空数组,并且这些数组总是有满足条件的“主要元素”
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
2. 解题思路
本题有一个地方需要注意,那就是 majority element 不能理解为众数,题目对 majority element 的定义是出现次数大于 ⌊ n/2 ⌋ 的元素,而众数则是出现次数最多的数。
一个万能的方法是,使用HashMap,存放所有出现的数字及其次数,然后找出出现次数最多的即可。这个方法对于众数和majority element 都可以使用。
但是因为 majority element 这样一个设定,还有很多方法和技巧可以用在本题中,下面就说两种适合本题但是不适合众数的方法。这两种思路都来自本题LeetCode的Solution (https://leetcode.com/problems/majority-element/solution/)
2.1 排序后取中间的数字
由于 majority element 的定义是出现次数大于 ⌊ n/2 ⌋ 的元素。所以当我们将所有数字按照递增或者递减的顺序排列好后,最中间的数字必定是 majority element 。如果n是偶数,那么最中间的两个数字都是majority element。
于是一种代码非常简洁的方法出现了:
实现代码
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length / 2];
}
}
2.2 分治法
把长度为n的数组从中间分成两个部分。左半部分中,找出次数最多的数 l,右半部分也找出次数最多的数 r。那么整个数组中,出现次数最多的数就是 l 和 r 两者中的一个了。然后再比较 l 和 r 在整个数组中出现的次数谁多,谁的次数多,谁就是整个数组的majority element。使用分治法一层一层递归下去,就可以求出整个数组的majority element了。
细心的读者一定会发现一个问题,左半部出现最多的数,和右半部分出现最多的数,就一定是整个数组出现最多的数吗?答案当然是否定的,比如下面整个例子:
n = 10
1 1 1 2 2 ,2 2 3 3 3
左半部分1的次数最多,右半部分3的次数最多,但是整体2的次数最多。那么遇到这种情况分治法还有效吗?
事实上,这种情况是不会出现的,原因还是在majority element的定义上。只有出现次大于 ⌊ n/2 ⌋ 的元素才是 majority element。这个数组中没有majority element,所以该情况不会出现。
实现代码
class Solution {
public int majorityElement(int[] nums) {
return recursion(nums,0,nums.length-1);
}
public int recursion(int[] nums,int begin,int end){
if (begin == end) {
return nums[begin];
}
int middle = (begin + end) / 2;
int left = recursion(nums, begin ,middle);//左半部分次数最多的数
int right = recursion(nums , middle+1 ,end);//右半部分次数最多的数
int leftTimes = CountTimes( nums, begin, end, left);
int rightTimes = CountTimes( nums, begin, end, right);
return (leftTimes > rightTimes ? left : right);
}
//计算从下标begin到下标end,数字a出现了多少次
public int CountTimes(int [] nums, int begin,int end, int a){
int t = 0;
for (int i = begin; i <= end ; i++ ) {
if (nums[i] == a) {
t++;
}
}
return t;
}
}