LeetCode#169 Majority Element

[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.

[My Answer]
class Solution {
public:
int majorityElement(vector<int>& nums) {
return element(nums, 0, nums.size()-1);
}
private:
int element(vector<int>&nums, int l, int r) {
if (l == r) return nums[l];
int mid = (l + r) / 2;
int _l = element(nums, l, mid);
int _r = element(nums, mid+1, r);
if (_l == _r) return _l;
if (count(nums.begin()+l, nums.begin()+r+1, _l) > count(nums.begin()+l, nums.begin()+r+1, _r)) return _l;
else return _r;
}
};

这道题是一道经典的可以用分治法解决的题。
首先理解题意,找到一个出现次数超过 ⌊ n/2 ⌋ 的数字,这个数字肯定是唯一的。
用分治法的想法就是把此数组不断划分成更小的数组,在更小的数组里解决这个问题,当n == 1 的时候,就只有一个数了。在合并的过程中,若两个子数组的众数不同,则在这个大数组里比较这两个众数出现的次数,选择出现次数多的数字。

用了分治法以后的时间复杂度为O(nlogn),比起特别暴力的每个数字算count有所进步,但其实也不咋地,应该是只超过了30%+的算法。看了一下比较快的方法是:
class Solution {
public:
int majorityElement(vector<int>& nums) {
int candidate = 0;
int count = 0;
for(int num:nums) {
if(count == 0) {
candidate = num;
count++;
} else {
if(candidate != num) {
count--;
} else {
count++;
}
}
}
return candidate;
}
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值