leetcode 169. 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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
两种解法,一种是排序后取中位数!
另外一种是用计数的方式,Moore voting algorithm 据说是叫这个,和选票一半以上的人当选一样,计票方法:如果是一张反对票一张赞成票则互相抵消。
class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ ans = nums[0] cnt = 1 for i in xrange(1, len(nums)): if cnt == 0: cnt = 1 ans = nums[i] elif nums[i] == ans: cnt += 1 else: cnt -= 1 return ans
另外我自己的解法是每两位计数一次,计数重复出现的数,见注释示例:
class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ #nums.sort() #return nums[len(nums)>>1] # 1 1 2=>1==1 ans=1, dup=2, last 2 dump it # 2 1 1=>2!=1, dup=0, ans=1 # 1 1 1 2=>1=1, dup=2, ans=1, 1!=2 # 1 2 3 1 1 1=>1!=2, dup=0, 3!=1, dup=0, 1==1, dup=2, ans=1 # 1 1 3 3 2 1 1=>1==1,dup=2, 3==3, dup-=2,dup=0, 2!=0, 1 is answer # 1 1 1 1 3 3 3 3 2 1 1=> ans = nums[0] dup_flag = 0 i = 1 while i<len(nums): if nums[i] == nums[i-1]: if nums[i] == ans: # check if is prev ans dup_flag += 2 else: if dup_flag >= 2: dup_flag -= 2 else: dup_flag = 2 ans = nums[i] i += 2 if len(nums) & 1 and dup_flag == 0: return nums[-1] return ans
最后一种是位运算:
Bit Manipulation
Another nice idea! The key lies in how to count the number of 1
's on a specific bit. Specifically, you need a mask
with a 1
on the i
-the bit and 0
otherwise to get the i
-th bit of each element in nums
. The code is as follows.
class Solution {
public:
int majorityElement(vector<int>& nums) {
int major = 0, n = nums.size();
for (int i = 0, mask = 1; i < 32; i++, mask <<= 1) {
int bitCounts = 0;
for (int j = 0; j < n; j++) {
if (nums[j] & mask) bitCounts++;
if (bitCounts > n / 2) {
major |= mask;
break;
}
}
}
return major;
}
};
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」