We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.
Example 1:
Input: nums = [3,2,3] Output: 3
Example 2:
Input: nums = [2,2,1,1,1,2,2] Output: 2
Constraints:
Follow-up: Could you solve the problem in linear time and in O(1) space?
求众数,如果使空间复杂度是O(1),用摩尔计数法: 代码如下:
class Solution { public: int majorityElement(vector<int>& nums) { int candidate = nums[0], cnt = 0, n = nums.size(); for (auto e: nums) { if (candidate == e) { cnt++; } else { if (cnt == 0) { candidate = e; cnt++; } else { cnt--; } } } cnt = 0; for (auto e: nums) { if (candidate == e) cnt++; } if (cnt > n / 2) return candidate; return -1; } };
类似题目: 229. Majority Element II
The text was updated successfully, but these errors were encountered:
No branches or pull requests
Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.
Example 1:
Example 2:
Constraints:
Follow-up: Could you solve the problem in linear time and in O(1) space?
求众数,如果使空间复杂度是O(1),用摩尔计数法:
代码如下:
类似题目:
229. Majority Element II
The text was updated successfully, but these errors were encountered: