[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.
Example 1:
Input: [3,2,3] Output: 3
Example 2:
Input: [2,2,1,1,1,2,2] Output: 2
给一个大小为n的数组,找出它的多数元素。数组非空,多数元素存在。多数元素:出现次数超过n/2的元素(超过数组长度一半)。
解法1: 用两个循环跟踪统计最多次数的元素。 T:O(n*n) S: O(1)
解法2: BST, T:O(nlogn) S: O(n)
解法3:Boyer-Moore多数投票算法 Boyer–Moore majority vote algorithm,T:O(n) S: O(1)
解法4: HashMap, T:O(n) S: O(n)
Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public class Solution { public int majorityElement( int [] num) { int major=num[ 0 ], count = 1 ; for ( int i= 1 ; i<num.length;i++){ if (count== 0 ){ count++; major=num[i]; } else if (major==num[i]){ count++; } else count--; } return major; } } |
Java:
1 2 3 4 5 6 7 8 9 10 11 | public class Solution { public int majorityElement( int [] nums) { int res = 0 , cnt = 0 ; for ( int num : nums) { if (cnt == 0 ) {res = num; ++cnt;} else if (num == res) ++cnt; else --cnt; } return res; } } |
Python: T: O(n), S: O(1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class Solution: def majorityElement( self , nums): idx, cnt = 0 , 1 for i in xrange ( 1 , len (nums)): if nums[idx] = = nums[i]: cnt + = 1 else : cnt - = 1 if cnt = = 0 : idx = i cnt = 1 return nums[idx] |
C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class Solution { public : int majorityElement(vector< int >& nums) { int ans = nums[0], cnt = 1; for ( const auto & i : nums) { if (i == ans) { ++cnt; } else { --cnt; if (cnt == 0) { ans = i; cnt = 1; } } } return ans; } }; |
类似题目:
[LeetCode] 229. Majority Element II 多数元素 II
All LeetCode Questions List 题目汇总
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步