Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情。
一、题目描述:
169. 多数元素 – 力扣(LeetCode) (leetcode-cn.com)
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋
的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入:[3,2,3]
输出:3
复制代码
示例 2:
输入:[2,2,1,1,1,2,2]
输出:2
复制代码
进阶:
尝试设计时间复杂度为 O(n)、空间复杂度为 O(1) 的算法解决此问题。
二、思路分析:
因为出现超过一半的数字,排序后肯定占据了中间位置。所以此题类似于求第K大问题,此时K为数组长度的一半,即中间值。那么就可以用快排的partation来切分,因为partation每次都会将一个元素放到正确的位置,当发现当前位置是中间位置时即可返回。
三、AC 代码:
public int majorityElement(int[] nums) {
int left = 0;
int right = nums.length - 1;
int middle = nums.length >>> 1;
int index = partation(left, right, nums);
while (index != middle) {
if (index > middle)
right = index - 1;
else
left = index + 1;
index = partation(left, right, nums);
}
return nums[index];
}
private int partation(int left, int right, int[] array) {
int temp = array[right];
while (left < right) {
while (left < right && array[left] <= temp)
left++;
array[right] = array[left];
while (left < right && array[right] > temp)
right--;
array[left] = array[right];
}
array[left] = temp;
return left;
}
复制代码
四、总结:
快排算是个不错的解法,另外官方提到的摩尔投票法,不太熟悉,需要研究下。
范文参考:
Java-3种方法(计数法/排序法/摩尔投票法) – 多数元素 – 力扣(LeetCode) (leetcode-cn.com)
【Chthollist】多数元素 (众数) :「摩尔投票法」&「哈希表」&「位运算」 – 多数元素 – 力扣(LeetCode) (leetcode-cn.com)
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END