Tag
Array/Divide and Conquer/Bit Manipulation
Difficulty
Easy
Description
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.
Code
- Array:
Moore Voting Algorithm
每找出两个不同的element,即成对删除count–,否则count++
时间复杂度O(n)
class Solution:
# @param {integer[]} nums
# @return {integer}
def majorityElement(self, nums):
count=0
major_Element=0
for num in nums:
if count==0:
major_Element=num
count=count+1
else:
if num==major_Element:
count =count+1
else:
count = count-1
return major_Element
- Divide and Conquer
将数组划分成两半,分别递归查找这部分的多数元素,如果相同,则为多数元素,否则为其中之一,判断其一即可
时间复杂度O(nlogn)
class Solution(object):
def majority(self,nums,left,right):
if left == right:
return nums[left]
mid = (left+right)/2
lm = self.majority(nums,left,mid)
rm = self.majority(nums,mid+1,right)
if lm == rm:
return lm
if nums[left:right+1].count(lm) > nums[left:right+1].count(rm):
return lm
else:
return rm
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return self.majority(nums,0,len(nums)-1)
- Bit Manipulation
统计int的32位上每一位的众数,每一位的众数即组成了Majority Element的每一位。
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;
}
};