Skip to content

[LeetCode] 169. Majority Element #17

New issue

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

Open
frdmu opened this issue Jul 15, 2021 · 0 comments
Open

[LeetCode] 169. Majority Element #17

frdmu opened this issue Jul 15, 2021 · 0 comments

Comments

@frdmu
Copy link
Owner

frdmu commented Jul 15, 2021

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:

  • n == nums.length
  • 1 <= n <= 5 * 104
  • -231 <= nums[i] <= 231 - 1
     

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant