1. 程式人生 > >169. Majority Element

169. Majority Element

個數 int pub always and you bsp urn floor

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.

找到一堆數中出現次數>n/2 的那個數。

普通解法。可能用map 或者二分,但是仔細想一想可以用o(n)的解法。

其實就是求這堆數的眾數。

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int n = nums.size();
        int can = nums[0];
        int cnt = 1;
        for (int i = 1; i < n; ++i) {
            if (nums[i] == can) cnt++;
            else {
                cnt--;
                
if (cnt == 0) can = nums[i],cnt = 1; } } return can; } };

.

169. Majority Element