<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>voting Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/voting/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/voting/</link>
	<description></description>
	<lastBuildDate>Sat, 14 Mar 2020 06:21:49 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.8</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>voting Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/voting/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 229. Majority Element II</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-229-majority-element-ii/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-229-majority-element-ii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 14 Mar 2020 06:21:09 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[Boyer–Moore]]></category>
		<category><![CDATA[majority element]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[voting]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6471</guid>

					<description><![CDATA[<p>Given an integer array of size&#160;n, find all elements that appear more than&#160;⌊ n/3 ⌋&#160;times. Note:&#160;The algorithm should run in linear time and in O(1)&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-229-majority-element-ii/">花花酱 LeetCode 229. Majority Element II</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given an integer array of size&nbsp;<em>n</em>, find all elements that appear more than&nbsp;<code>⌊ n/3 ⌋</code>&nbsp;times.</p>



<p><strong>Note:&nbsp;</strong>The algorithm should run in linear time and in O(1) space.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> [3,2,3]
<strong>Output:</strong> [3]</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> [1,1,1,3,3,2,2,2]
<strong>Output:</strong> [1,2]</pre>



<h2><strong>Solution: Boyer–Moore Voting Algorithm</strong></h2>



<p>Time complexity: O(n)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; majorityElement(vector&lt;int&gt;&amp; nums) {
    int n1 = 0;
    int c1 = 0;
    int n2 = 1;
    int c2 = 0;
    for (int num : nums) {
      if (num == n1) {
        ++c1;
      } else if (num == n2) {
        ++c2;
      } else if (c1 == 0) {
        n1 = num;
        c1 = 1;
      } else if (c2 == 0) {
        n2 = num;
        c2 = 1;
      } else {
        --c1;
        --c2;
      }
    }
    
    c1 = c2 = 0;
    for (int num : nums) {
      if (num == n1) ++c1;
      else if (num == n2) ++c2;
    }
    
    const int c = nums.size() / 3;
    vector&lt;int&gt; ans;
    if (c1 &gt; c) ans.push_back(n1);
    if (c2 &gt; c) ans.push_back(n2);
    return ans;
  }
};</pre>
</div></div>



<div class="responsive-tabs">
<h2 class="tabtitle">Python3</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def majorityElement(self, nums: List[int]) -&gt; List[int]:
    n1, c1, n2, c2 = 0, 0, 1, 0
    for num in nums:
      if num == n1: c1 += 1
      elif num == n2: c2 += 1
      elif c1 == 0: n1, c1 = num, 1
      elif c2 == 0: n2, c2 = num, 1
      else: c1, c2 = c1 - 1, c2 -1
    
    c1, c2 = 0, 0
    for num in nums:
      if num == n1: c1 += 1
      elif num == n2: c2 += 1
    
    ans = []
    if c1 &gt; len(nums) // 3: ans.append(n1)
    if c2 &gt; len(nums) // 3: ans.append(n2)
    return ans</pre>
</div></div>



<h2><strong>Related Problem</strong></h2>



<ul><li><a href="https://zxi.mytechroad.com/blog/divide-and-conquer/leetcode-169-majority-element/">https://zxi.mytechroad.com/blog/divide-and-conquer/leetcode-169-majority-element/</a></li></ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-229-majority-element-ii/">花花酱 LeetCode 229. Majority Element II</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-229-majority-element-ii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱  LeetCode 169. Majority Element</title>
		<link>https://zxi.mytechroad.com/blog/divide-and-conquer/leetcode-169-majority-element/</link>
					<comments>https://zxi.mytechroad.com/blog/divide-and-conquer/leetcode-169-majority-element/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 05 Nov 2017 06:55:23 +0000</pubDate>
				<category><![CDATA[Bit]]></category>
		<category><![CDATA[Divide and conquer]]></category>
		<category><![CDATA[Easy]]></category>
		<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[bit]]></category>
		<category><![CDATA[voting]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=738</guid>

					<description><![CDATA[<p>题目大意：给你一个数组，其中一个数出现超过n/2次，问你出现次数最多的那个数是什么？ Problem: 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&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/divide-and-conquer/leetcode-169-majority-element/">花花酱  LeetCode 169. Majority Element</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/LPIvL-jvGdA?feature=oembed" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen></iframe></p>
<p>题目大意：给你一个数组，其中一个数出现超过n/2次，问你出现次数最多的那个数是什么？</p>
<p><strong>Problem:</strong></p>
<p>Given an array of size <i>n</i>, find the majority element. The majority element is the element that appears <b>more than</b> <code>⌊ n/2 ⌋</code> times.</p>
<p>You may assume that the array is non-empty and the majority element always exist in the array.</p>
<p><strong>Ideas:</strong></p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/169-ep101.png"><img class="alignnone size-full wp-image-743" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/169-ep101.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/169-ep101.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/169-ep101-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/169-ep101-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/169-ep101-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script></p>
<p><ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-2404451723245401" data-ad-slot="7983117522"></ins><br />
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<p><strong>Solution 1:</strong></p>
<p>Hash table O(n) / O(n)</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime : 23 ms
class Solution {
public:
    int majorityElement(vector&lt;int&gt;&amp; nums) {
        unordered_map&lt;int, int&gt; count;
        const int n = nums.size();
        for (const int num : nums)
            if (++count[num] &gt; n / 2) return num;
        return -1;
    }
};</pre><p>&nbsp;</p>
<p><strong>Solution 2:</strong></p>
<p>BST O(nlogk) / O(n)</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime : 19 ms
class Solution {
public:
    int majorityElement(vector&lt;int&gt;&amp; nums) {
        map&lt;int, int&gt; count;
        const int n = nums.size();
        for (const int num : nums)
            if (++count[num] &gt; n / 2) return num;
        return -1;
    }
};</pre><p>&nbsp;</p>
<p><strong>Solution 3:</strong></p>
<p>Randomization O(n) / O(1)</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 19 ms
class Solution {
public:
    int majorityElement(vector&lt;int&gt;&amp; nums) {
        srand(time(nullptr));
        const int n = nums.size();
        while (true) {
            const int index = rand() % n;
            const int majority = nums[index];
            int count = 0;
            for (const int num : nums)
                if (num == majority &amp;&amp; ++count &gt; n/2) return num;
        }
        return -1;
    }
};</pre><p>&nbsp;</p>
<p><strong>Solution 4:</strong></p>
<p>Bit voting O(n) / O(1)</p><pre class="crayon-plain-tag">class Solution {
public:
    int majorityElement(vector&lt;int&gt;&amp; nums) {
        const int n = nums.size();
        int majority = 0;        
        for (int i = 0; i &lt; 32; ++i) {
            int mask = 1 &lt;&lt; i;
            int count = 0;
            for (const int num : nums)
                if ((num &amp; mask) &amp;&amp; (++count &gt; n /2)) {
                    majority |= mask;
                    break;
                }
        }
        return majority;
    }
};</pre><p>&nbsp;</p>
<p><strong>Solution 5:</strong></p>
<p>Moore Voting O(n) / O(1)</p><pre class="crayon-plain-tag">class Solution {
public:
    int majorityElement(vector&lt;int&gt;&amp; nums) {
        int majority = nums.front();
        int count = 0;
        
        for (const int num : nums) {
            if (num == majority) ++count;
            else if (--count == 0) {
                count = 1;
                majority = num;
            }
        }
        
        return majority;
    }
};</pre><p>&nbsp;</p>
<p>Solution 6:</p>
<p>Full sorting O(nlogn) / O(1)</p><pre class="crayon-plain-tag">class Solution {
public:
    int majorityElement(vector&lt;int&gt;&amp; nums) {
        std::sort(nums.begin(), nums.end());
        return nums[nums.size()/2];
    }
};</pre><p>&nbsp;</p>
<p>Solution 7:</p>
<p>Partial sorting O(n) / O(1)</p><pre class="crayon-plain-tag">class Solution {
public:
    int majorityElement(vector&lt;int&gt;&amp; nums) {
        nth_element(nums.begin(), nums.begin() + nums.size() / 2, nums.end());
        return nums[nums.size() / 2];
    }
};</pre><p>&nbsp;</p>
<p>Solution 8:</p>
<p>Divide and conquer O(nlogn) / O(logn)</p><pre class="crayon-plain-tag">class Solution {
public:
    int majorityElement(vector&lt;int&gt;&amp; nums) {
        return majorityElement(nums, 0, nums.size() - 1);
    }
private:
    int majorityElement(const vector&lt;int&gt;&amp; nums, int l, int r) {
        if (l == r) return nums[l];
        const int m = l + (r - l) / 2;
        const int ml = majorityElement(nums, l, m);
        const int mr = majorityElement(nums, m + 1, r);
        if (ml == mr) return ml;
        return count(nums.begin() + l, nums.begin() + r + 1, ml) &gt;
               count(nums.begin() + l, nums.begin() + r + 1, mr)
               ? ml : mr;
    }
};</pre><p>Divide and conquer O(nlogn) / O(logn)</p><pre class="crayon-plain-tag">class Solution {
public:
    int majorityElement(vector&lt;int&gt;&amp; nums) {
        return majorityElement(nums, 0, nums.size() - 1).first;
    }
private:
    pair&lt;int, int&gt; majorityElement(const vector&lt;int&gt;&amp; nums, int l, int r) {
        if (l == r) return {nums[l], 1};
        int mid = l + (r - l) / 2;
        auto ml = majorityElement(nums, l, mid);
        auto mr = majorityElement(nums, mid + 1, r);
        if (ml.first == mr.first) return { ml.first, ml.second + mr.second };
        if (ml.second &gt; mr.second)
            return { ml.first, ml.second + count(nums.begin() + mid + 1, nums.begin() + r + 1, ml.first) };
        else
            return { mr.first, mr.second + count(nums.begin() + l, nums.begin() + mid + 1, mr.first) };
    }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/divide-and-conquer/leetcode-169-majority-element/">花花酱  LeetCode 169. Majority Element</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/divide-and-conquer/leetcode-169-majority-element/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
