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.
思路: 1. 有题目可以知道,所求的元素的数目大于⌊ n/2 ⌋,也就意味着,且该元素是存在的。
2. 通过每寻找到两个不同的元素的时候,就一块删除掉,剩下最后的就是所求的元素。(因为该元素数目大于⌊ n/2 ⌋该,也就是一半,所以一次 删除两个不同元素最后就是目标元素)
具体代码实现如下:
class Solution { public: int majorityElement(vector<int>& nums) { int majority = 0; int count = 0; for(int i = 0; i < nums.size(); i++){ if(count == 0){ majority = nums[i]; count = 1; } else{ if(nums[i] == majority) count ++; else count --; } } return majority; } };