Title address: https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof/
Title description
There is a number in the array that appears more than half the length of the array. Please find this number. You can assume that the array is non-empty, and there will always be a majority of elements in a given array.
Example questions
Example 1:
Input: [1, 2, 3, 2, 2, 2, 5, 4, 2]
Output: 2
Problem-solving ideas
Idea 1: Sort the array first, and then take the middle number, because the middle element must be more than half of the number after sorting.
Idea 2: The hash table counts the number of occurrences of each number, and returns the element when the number of occurrences exceeds half.
Idea 3: Use the voting method to conduct elections, each element can participate in the majority selection, if you encounter the same as yourself, you will add one vote, that is vote ++, if you encounter a different vote from yourself, that is vote--, and the final What comes down is what the title requires.
Idea 4: More than half of the numbers appear more often than all other numbers combined
Program source code
Idea 1
class Solution { public: int majorityElement(vector<int>& nums) { sort(nums.begin(), nums.end()); return nums[nums.size()/2]; } };
Idea 2
class Solution { public: int majorityElement(vector<int>& nums) { unordered_map<int, int> mp; for(int i = 0; i < nums.size(); i++) { mp[nums[i]]++; } for(int j = 0; j < nums.size(); j++) { if(mp[nums[j]] > nums.size() / 2) return nums[j]; } return 0; } };
Idea 3
class Solution { public: int majorityElement(vector<int>& nums) { int vote = 0; int majority; //众数 for(int i = 0; i < nums.size(); i++) { if(vote == 0) majority = nums[i]; if(nums[i] == majority) vote++; else vote--; } return majority; } };
Idea 4
class Solution { public: int majorityElement(vector<int>& nums) { int cnt = 1; int res = nums[0]; for(int i = 1; i < nums.size(); i++) { if(res == nums[i]) cnt++; else cnt--; if(cnt == 0) { res = nums[i]; cnt = 1; } } return res; } };