Leetcode Majority Element系列 摩尔投票法

来源:互联网 发布:淘宝怎么看卖家电话 编辑:程序博客网 时间:2024/05/16 09:08

leetcode #169 Majority Element

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.

class Solution{public:    int majorityElement(vector<int>& nums) {        int ans, cnt = 0;        for(int n: nums){            if (cnt == 0 || n == ans){                cnt++; ans = n;            }            else                cnt--;        }        return ans;    }};

leetcode #229 Majority Element II

Given an integer array of size n, find all elements that appear more than⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

public:    vector<int> majorityElement(vector<int>& nums) {        int cnt1 = 0, cnt2 = 0;        int a, b;        for(int n: nums){            if (cnt1 == 0 || n == a){                cnt1++; a = n;            }            else if (cnt2 == 0 || n == b){                cnt2++; b = n;            }            else{                cnt1--; cnt2--;            }        }        cnt1 = cnt2 = 0;        for(int n: nums){            if (n == a)   cnt1++;            else if (n == b) cnt2++;        }        vector<int> result;        if (cnt1 > nums.size()/3)   result.push_back(a);        if (cnt2 > nums.size()/3)   result.push_back(b);        return result;    }};


0 0
原创粉丝点击