[LeetCode] Majority Element II,leetcodemajority

來源:互聯網
上載者:User

[LeetCode] Majority Element II,leetcodemajority

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.

解題思路

摩爾投票法。投票法的核心是找出兩個候選眾數進行投票,需要兩遍遍曆,第一遍曆找出兩個候選眾數,第二遍遍曆重新投票驗證這兩個候選眾數是否為眾數即可。

實現代碼

C++:

class Solution {public:    vector<int> majorityElement(vector<int>& nums) {        vector<int> res;        int m = 0, n = 0, cm = 0, cn = 0;        for (int i = 0; i < nums.size(); i++)        {            if (nums[i] == m)            {                cm++;            }            else if (nums[i] == n)            {                cn++;            }            else if (cm == 0)            {                m = nums[i];                cm = 1;            }            else if (cn == 0)            {                n = nums[i];                cn = 1;            }            else            {                --cm;                --cn;            }        }        cm = cn = 0;        for (auto& a : nums)        {            if (a == m)            {                cm++;            }            else if (a== n)            {                cn++;            }        }        if (cm > nums.size() / 3)        {            res.push_back(m);        }        if (cn > nums.size() / 3)        {            res.push_back(n);        }        return res;    }};

Java:

public class Solution {    public List<Integer> majorityElement(int[] nums) {        List<Integer> res = new ArrayList<Integer>();        int m = 0, n = 0, cm = 0, cn = 0;        for (int a : nums) {            if (a == m) {                ++cm;            } else if (a == n) {                ++cn;            } else if (cm == 0) {                m = a;                cm = 1;            } else if (cn == 0) {                n = a;                cn = 1;            } else {                --cm;                --cn;            }        }        cm = cn = 0;        for (int a : nums){            if (a == m) {                ++cm;            } else if (a == n) {                ++cn;            }        }        if (cm > nums.length / 3) {            res.add(m);        }        if (cn > nums.length / 3) {            res.add(n);        }        return res;    }}

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.