多数元素
给定一个大小为 *n *的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋
的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入:[3,2,3]输出:3
示例 2:
输入:[2,2,1,1,1,2,2]输出:2
方法一:排序+取中间元素
public int majorityElement(int[] nums) {
int n = nums.length;
Arrays.sort(nums);
return nums[n / 2];
}
方法二:摩尔投票
public int majorityElement(int[] nums) {
int candidate = 0;
int count = 0;
for (int num : nums) {
count += candidate == num ? 1 : -1;
if (count < 0) {
candidate = num;
count = 1;
}
}
return candidate;
}