题目:
Given an array of integers, the majority number is the number that occurs more than half
of the size of the array. Find it.
Notice
You may assume that the array is non-empty and the majority number always exist in the array.
Have you met this question in a real interview?
Yes
Example
Given [1, 1, 1, 1, 2, 2, 2]
, return 1
题解:
摩尔投票法
Solution 1 ()
class Solution { public: int majorityNumber(vector<int> nums) { int cnt = 0; int res = nums[0]; for(auto n : nums) { if (n == res) { cnt++; continue; } else { if(--cnt <= 0) { cnt = 1; res = n; } } } return res; } };
时间: 2024-10-20 21:27:53