find the majority element

this is a question from leetcode:

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.

If you want to get the best solution, then you must analyst and make use of all the information provided in the problem.

question analysis:
the key hint is that the majority element always exist. So that means that the count of majority element is great than the count of all other element, so the
count(majority) - count(others) > 0.

below is the best solution:

public int majorityElement(int[] nums) {
int result = nums[0];
int count = 1;
for(int i = 1; i < nums.length; i++){
if(result == nums[i]){
count++;
}else{
count--;
}
if(count == 0){
result = nums[i];
count++;
}
}
return result;
}
### C++ 实现一维数组投票模型算法 在一维数组投票模型中,目标是从给定的一维数组中找到出现次数超过一半的元素。该问题可以通过 Boyer-Moore 投票算法高效解决。 #### 算法描述 Boyer-Moore 投票算法的核心思想是在一次遍历过程中维护一个候选众数及其计数器。当遇到相同的元素时增加计数器;遇到不同的元素则减少计数器。如果计数器变为零,则更换新的候选众数并重置计数器[^1]。 #### 代码实现 以下是使用 C++ 实现 Boyer-Moore 投票算法的具体代码: ```cpp #include <iostream> #include <vector> using namespace std; // Function to find the majority element (if exists) using Boyer-Moore Voting Algorithm int boyer_moore_voting(const vector<int>& nums) { int count = 0; int candidate = -1; // First pass: Find a potential candidate for majority element for (int num : nums) { if (count == 0) { candidate = num; } count += (num == candidate ? 1 : -1); } return candidate; } // Verify that the candidate is indeed the majority element bool verify_majority(const vector<int>& nums, int candidate) { int count = 0; for (int num : nums) { if (num == candidate) { ++count; } } return count > nums.size() / 2; } int main() { vector<int> nums = {2, 2, 1, 1, 1, 2, 2}; int candidate = boyer_moore_voting(nums); if (verify_majority(nums, candidate)) { cout << "Majority Element found: " << candidate << endl; } else { cout << "No Majority Element" << endl; } return 0; } ``` 此程序首先通过 `boyer_moore_voting` 函数找出可能存在的多数元素,再利用 `verify_majority` 函数验证这个候选人是否确实是多数元素。最终输出结果表明是否存在这样的元素以及其值是多少。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值