<?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>O(1) Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/o1/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/o1/</link>
	<description></description>
	<lastBuildDate>Mon, 09 Mar 2020 07:41:46 +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>O(1) Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/o1/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 258. Add Digits</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-258-add-digits/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-258-add-digits/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 09 Mar 2020 07:34:16 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[digits]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[O(1)]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6426</guid>

					<description><![CDATA[<p>Given a non-negative integer&#160;num, repeatedly add all its digits until the result has only one digit. Example: Input: 38 Output: 2 Explanation: The process is&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-258-add-digits/">花花酱 LeetCode 258. Add Digits</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 a non-negative integer&nbsp;<code>num</code>, repeatedly add all its digits until the result has only one digit.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> <code>38</code>
<strong>Output:</strong> 2 
<strong>Explanation: </strong>The process is like: <code>3 + 8 = 11</code>, <code>1 + 1 = 2</code>. 
&nbsp;            Since <code>2</code> has only one digit, return it.
</pre>



<p><strong>Follow up:</strong><br>Could you do it without any loop/recursion in O(1) runtime?</p>



<h2><strong>Solution 1: Simulation</strong></h2>



<p>Time complexity: O(logn)<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:
  int addDigits(int num) {
    int n = num;
    while (n &gt;= 10) {      
      int t = n;
      n = 0;
      while (t) {
        n += t % 10;
        t /= 10;
      }
    }
    return n;
  }
};</pre>
</div></div>



<h2><strong>Solution 2: Math</strong></h2>



<p><a href="https://en.wikipedia.org/wiki/Digital_root#Congruence_formula">https://en.wikipedia.org/wiki/Digital_root#Congruence_formula</a></p>



<p>Digit root = num % 9 if num % 9 != 0 else min(num, 9) e.g. 0 or 9</p>



<p>Time complexity: O(1)<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:
  int addDigits(int num) {    
    return num % 9 ? num % 9 : min(num, 9);
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-258-add-digits/">花花酱 LeetCode 258. Add Digits</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/simulation/leetcode-258-add-digits/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1323. Maximum 69 Number</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-1323-maximum-69-number/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-1323-maximum-69-number/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 21 Jan 2020 02:57:05 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[max]]></category>
		<category><![CDATA[O(1)]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6120</guid>

					<description><![CDATA[<p>Given a positive integer&#160;num&#160;consisting only of digits 6 and 9. Return the maximum number you can get by changing&#160;at most&#160;one digit (6 becomes 9, and&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1323-maximum-69-number/">花花酱 LeetCode 1323. Maximum 69 Number</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 a positive integer&nbsp;<code>num</code>&nbsp;consisting only of digits 6 and 9.</p>



<p>Return the maximum number you can get by changing&nbsp;<strong>at most</strong>&nbsp;one digit (6 becomes 9, and 9 becomes 6).</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = 9669
<strong>Output:</strong> 9969
<strong>Explanation:</strong> 
Changing the first digit results in 6669.
Changing the second digit results in 9969.
Changing the third digit results in 9699.
Changing the fourth digit results in 9666.&nbsp;
The maximum number is 9969.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = 9996
<strong>Output:</strong> 9999
<strong>Explanation:</strong> Changing the last digit 6 to 9 results in the maximum number.</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = 9999
<strong>Output:</strong> 9999
<strong>Explanation:</strong> It is better not to apply any change.</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= num &lt;= 10^4</code></li><li><code>num</code>&#8216;s digits are 6 or 9.</li></ul>



<h2><strong>Solution: Greedy</strong></h2>



<p>Replace the highest 6 to 9, if no 6, return the original number.</p>



<p>Time complexity: O(1)<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:
  int maximum69Number (int num) {
    string s = to_string(num);
    for (int i = 0; i &lt; s.length(); ++i) {
      if (s[i] == '6') {
        s[i] = '9';
        return stoi(s);
      }
    }
    return num;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1323-maximum-69-number/">花花酱 LeetCode 1323. Maximum 69 Number</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/greedy/leetcode-1323-maximum-69-number/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 1276. Number of Burgers with No Waste of Ingredients</title>
		<link>https://zxi.mytechroad.com/blog/math/1276-number-of-burgers-with-no-waste-of-ingredients/</link>
					<comments>https://zxi.mytechroad.com/blog/math/1276-number-of-burgers-with-no-waste-of-ingredients/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 02 Dec 2019 07:00:13 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(1)]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5908</guid>

					<description><![CDATA[<p>Given two integers&#160;tomatoSlices&#160;and&#160;cheeseSlices. The ingredients of different burgers are as follows: Jumbo Burger:&#160;4 tomato slices&#160;and 1 cheese slice. Small Burger:&#160;2 Tomato slices&#160;and 1 cheese slice.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/1276-number-of-burgers-with-no-waste-of-ingredients/">花花酱 1276. Number of Burgers with No Waste of Ingredients</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 two integers&nbsp;<code>tomatoSlices</code>&nbsp;and&nbsp;<code>cheeseSlices</code>. The ingredients of different burgers are as follows:</p>



<ul><li><strong>Jumbo Burger:</strong>&nbsp;4 tomato slices&nbsp;and 1 cheese slice.</li><li><strong>Small Burger:</strong>&nbsp;2 Tomato slices&nbsp;and 1 cheese slice.</li></ul>



<p>Return&nbsp;<code>[total_jumbo, total_small]</code>&nbsp;so that the number of remaining&nbsp;<code>tomatoSlices</code>&nbsp;equal to 0 and the number of remaining&nbsp;<code>cheeseSlices</code>&nbsp;equal to 0. If it is not possible to make the remaining&nbsp;<code>tomatoSlices</code>&nbsp;and&nbsp;<code>cheeseSlices</code>&nbsp;equal to 0 return&nbsp;<code>[]</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> tomatoSlices = 16, cheeseSlices = 7
<strong>Output:</strong> [1,6]
<strong>Explantion:</strong> To make one jumbo burger and 6 small burgers we need 4*1 + 2*6 = 16 tomato and 1 + 6 = 7 cheese. There will be no remaining ingredients.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> tomatoSlices = 17, cheeseSlices = 4
<strong>Output:</strong> []
<strong>Explantion:</strong> There will be no way to use all ingredients to make small and jumbo burgers.
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> tomatoSlices = 4, cheeseSlices = 17
<strong>Output:</strong> []
<strong>Explantion:</strong> Making 1 jumbo burger there will be 16 cheese remaining and making 2 small burgers there will be 15 cheese remaining.
</pre>



<p><strong>Example 4:</strong></p>



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



<p><strong>Example 5:</strong></p>



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



<p><strong>Constraints:</strong></p>



<ul><li><code>0 &lt;= tomatoSlices &lt;= 10^7</code></li><li><code>0 &lt;= cheeseSlices &lt;= 10^7</code></li></ul>



<h2><strong>Solution: Math</strong></h2>



<p>Time complexity: O(1)<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; numOfBurgers(int T, int C) {
    // Jumbo = x, small = y
    // 4x + 2y = T
    // x + y = C
    // x = (T - 2C) / 2
    int x = T / 2 - C;
    int y = C - x;
    if (4 * x + 2 * y == T &amp;&amp; x &gt;= 0 &amp;&amp; y &gt;= 0) return {x, y};
    return {};
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/1276-number-of-burgers-with-no-waste-of-ingredients/">花花酱 1276. Number of Burgers with No Waste of Ingredients</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/math/1276-number-of-burgers-with-no-waste-of-ingredients/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 190. Reverse Bits</title>
		<link>https://zxi.mytechroad.com/blog/bit/leetcode-190-reverse-bits/</link>
					<comments>https://zxi.mytechroad.com/blog/bit/leetcode-190-reverse-bits/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 30 Sep 2019 08:32:29 +0000</pubDate>
				<category><![CDATA[Bit]]></category>
		<category><![CDATA[bit]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[O(1)]]></category>
		<category><![CDATA[reverse]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5646</guid>

					<description><![CDATA[<p>Reverse bits of a given 32 bits unsigned integer. Example 1: Input: 00000010100101000001111010011100 Output: 00111001011110000010100101000000 Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-190-reverse-bits/">花花酱 LeetCode 190. Reverse Bits</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 190. Reverse Bits - 刷题找工作 EP284" width="500" height="375" src="https://www.youtube.com/embed/K0EHvvbUdEg?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Reverse bits of a given 32 bits unsigned integer.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> 00000010100101000001111010011100
<strong>Output:</strong> 00111001011110000010100101000000
<strong>Explanation: </strong>The input binary string <strong>00000010100101000001111010011100</strong> represents the unsigned integer 43261596, so return 964176192 which its binary representation is <strong>00111001011110000010100101000000</strong>.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> 11111111111111111111111111111101
<strong>Output:</strong> 10111111111111111111111111111111
<strong>Explanation: </strong>The input binary string <strong>11111111111111111111111111111101</strong> represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is <strong>10101111110010110010011101101001</strong>.</pre>



<p><strong>Note:</strong></p>



<ul><li>Note that in some languages such as Java, there is no unsigned integer type. In this case, both input and output will be given as signed integer type and should not affect your implementation, as the internal binary representation of the integer is the same whether it is signed or unsigned.</li><li>In Java,&nbsp;the compiler represents the signed integers using&nbsp;<a href="https://en.wikipedia.org/wiki/Two%27s_complement" target="_blank" rel="noreferrer noopener">2&#8217;s complement notation</a>. Therefore, in&nbsp;<strong>Example 2</strong>&nbsp;above the input represents the signed integer&nbsp;<code>-3</code>&nbsp;and the output represents the signed integer&nbsp;<code>-1073741825</code>.</li></ul>



<p><strong>Follow up</strong>:</p>



<p>If this function is called many times, how would you optimize it?</p>



<p>Solution: Bit operation</p>



<p>Time complexity: O(1)<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:
  uint32_t reverseBits(uint32_t n) {
    uint32_t ans = 0;
    for (int i = 0; i &lt; 32; ++i) {
      ans &lt;&lt;= 1;
      ans |= n &amp; 1;      
      n &gt;&gt;= 1;
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-190-reverse-bits/">花花酱 LeetCode 190. Reverse Bits</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/bit/leetcode-190-reverse-bits/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 73. Set Matrix Zeroes</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-73-set-matrix-zeroes/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-73-set-matrix-zeroes/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 09 Feb 2019 19:32:10 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[constant space]]></category>
		<category><![CDATA[in place]]></category>
		<category><![CDATA[O(1)]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4806</guid>

					<description><![CDATA[<p>Given a&#160;m&#160;x&#160;n&#160;matrix, if an element is 0, set its entire row and column to 0. Do it&#160;in-place. Example 1: Input: [ &#160; [1,1,1], &#160; [1,0,1],&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-73-set-matrix-zeroes/">花花酱 LeetCode 73. Set Matrix Zeroes</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 a&nbsp;<em>m</em>&nbsp;x&nbsp;<em>n</em>&nbsp;matrix, if an element is 0, set its entire row and column to 0. Do it&nbsp;<a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank" rel="noreferrer noopener"><strong>in-place</strong></a>.</p>



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



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



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



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



<p><strong>Follow up:</strong></p>



<ul><li>A straight forward solution using O(<em>m</em><em>n</em>) space is probably a bad idea.</li><li>A simple improvement uses O(<em>m</em>&nbsp;+&nbsp;<em>n</em>) space, but still not the best solution.</li><li>Could you devise a constant space solution?</li></ul>



<h2><strong>Solution 1</strong></h2>



<p>Use two arrays to track whether the i-th row / j-th column need to be zeroed.</p>



<p>Time complexity: O(mn)<br>Space complexity: O(m+n)</p>



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

<pre class="crayon-plain-tag">class Solution {
public:
  void setZeroes(vector&lt;vector&lt;int&gt;&gt;&amp; matrix) {
    const int m = matrix.size();
    const int n = matrix[0].size();
    vector&lt;int&gt; rows(m);
    vector&lt;int&gt; cols(n);
    for (int i = 0; i &lt; m; ++i)
      for (int j = 0; j &lt; n; ++j) {
        rows[i] |= (matrix[i][j] == 0);
        cols[j] |= (matrix[i][j] == 0);
      }
    for (int i = 0; i &lt; m; ++i)
      for (int j = 0; j &lt; n; ++j)
        if (rows[i] || cols[j]) matrix[i][j] = 0;        
  }
};</pre>
</div></div>



<h2><strong>Solution 2</strong></h2>



<p>Use the first row / first col to indicate whether the i-th row / j-th column need be zeroed.</p>



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

<pre class="crayon-plain-tag">class Solution {
public:
  void setZeroes(vector&lt;vector&lt;int&gt;&gt;&amp; matrix) {
    const int m = matrix.size();
    const int n = matrix[0].size();
    
    bool col0 = false;
    bool row0 = false;
    
    for (int i = 0; i &lt; m; ++i) 
      col0 |= (matrix[i][0] == 0);
    for (int j = 0; j &lt; n; ++j) 
      row0 |= (matrix[0][j] == 0);
    
    for (int i = 1; i &lt; m; ++i)
      for (int j = 1; j &lt; n; ++j)
        if (matrix[i][j] == 0)
          matrix[0][j] = matrix[i][0] = 0;      
    
    for (int i = 1; i &lt; m; ++i)
      for (int j = 1; j &lt; n; ++j)
        if (matrix[i][0] == 0 || matrix[0][j] == 0)
          matrix[i][j] = 0;
    
    if (row0)
      for (int j = 0; j &lt; n; ++j) 
        matrix[0][j] = 0;
    
    if (col0)
      for (int i = 0; i &lt; m; ++i) 
        matrix[i][0] = 0;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-73-set-matrix-zeroes/">花花酱 LeetCode 73. Set Matrix Zeroes</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-73-set-matrix-zeroes/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 501. Find Mode in Binary Search Tree</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-501-find-mode-in-binary-search-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-501-find-mode-in-binary-search-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 19 Jul 2018 07:53:28 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[mode]]></category>
		<category><![CDATA[O(1)]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3217</guid>

					<description><![CDATA[<p>Problem Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST. Assume a BST is defined&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-501-find-mode-in-binary-search-tree/">花花酱 LeetCode 501. Find Mode in Binary Search Tree</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>Given a binary search tree (BST) with duplicates, find all the <a href="https://en.wikipedia.org/wiki/Mode_(statistics)" target="_blank" rel="noopener">mode(s)</a> (the most frequently occurred element) in the given BST.</p>
<p>Assume a BST is defined as follows:</p>
<ul>
<li>The left subtree of a node contains only nodes with keys <b>less than or equal to</b> the node&#8217;s key.</li>
<li>The right subtree of a node contains only nodes with keys <b>greater than or equal to</b> the node&#8217;s key.</li>
<li>Both the left and right subtrees must also be binary search trees.</li>
</ul>
<p>&nbsp;</p>
<p>For example:<br />
Given BST <code>[1,null,2,2]</code>,</p><pre class="crayon-plain-tag">1
    \
     2
    /
   2</pre><p>return <code>[2]</code>.</p>
<p><b>Note:</b> If a tree has more than one mode, you can return them in any order.</p>
<p><b>Follow up:</b> Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).</p>
<h1>Solution1: Recursion w/ extra space</h1>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(n)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 8 ms
class Solution {
public:
  vector&lt;int&gt; findMode(TreeNode* root) {            
    inorder(root);    
    return ans_;
  }
private:
  int val_ = 0;
  int count_ = 0;  
  int max_count_ = 0;
  vector&lt;int&gt; ans_;
  
  void inorder(TreeNode* root) {
    if (root == nullptr) return;
    inorder(root-&gt;left);
    visit(root-&gt;val);
    inorder(root-&gt;right);
  }
  
  void visit(int val) {
    if (count_ &gt; 0 &amp;&amp; val == val_) {
      ++count_;   
    } else {
      val_ = val;
      count_ = 1;
    }
    
    if (count_ &gt; max_count_) {
      max_count_ = count_;
      ans_.clear();
    }
    
    if (count_ == max_count_)
      ans_.push_back(val);
  }
};</pre><p>&nbsp;</p>
<h1><strong>Solution2: Recursion w/o extra space</strong></h1>
<p>Two passes. First pass to find the count of the mode, second pass to collect all the modes.</p>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(1)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 8 ms
class Solution {
public:
  vector&lt;int&gt; findMode(TreeNode* root) {            
    inorder(root);    
    mode_count_ = max_count_;    
    count_ = 0;
    inorder(root);
    return ans_;
  }
private:
  int val_ = 0;
  int count_ = 0;
  int mode_count_ = INT_MAX;
  int max_count_ = 0;
  vector&lt;int&gt; ans_;
  
  void inorder(TreeNode* root) {
    if (root == nullptr) return;
    inorder(root-&gt;left);
    visit(root-&gt;val);
    inorder(root-&gt;right);
  }
  
  void visit(int val) {
    if (count_ &gt; 0 &amp;&amp; val == val_) {
      ++count_;      
    } else {
      val_ = val;
      count_ = 1;
    }
    
    if (count_ &gt; max_count_)
      max_count_ = count_;
    
    if (count_ == mode_count_)
      ans_.push_back(val);
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-501-find-mode-in-binary-search-tree/">花花酱 LeetCode 501. Find Mode in Binary Search Tree</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/tree/leetcode-501-find-mode-in-binary-search-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 432. All O`one Data Structure</title>
		<link>https://zxi.mytechroad.com/blog/data-structure/leetcode-432-all-oone-data-structure/</link>
					<comments>https://zxi.mytechroad.com/blog/data-structure/leetcode-432-all-oone-data-structure/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 07 Apr 2018 04:44:37 +0000</pubDate>
				<category><![CDATA[Data Structure]]></category>
		<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[List]]></category>
		<category><![CDATA[data structure]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[O(1)]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2434</guid>

					<description><![CDATA[<p>Problem 题目大意：设计一种数据结构，支持inc/dec/getmaxkey/getminkey操作，必须都在O(1)时间内完成。 https://leetcode.com/problems/all-oone-data-structure/description/ Implement a data structure supporting the following operations: Inc(Key) &#8211; Inserts a new key with value 1. Or increments an existing key by&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/data-structure/leetcode-432-all-oone-data-structure/">花花酱 LeetCode 432. All O`one Data Structure</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/wYqLisoH80w?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<h1>Problem</h1>
<p>题目大意：设计一种数据结构，支持inc/dec/getmaxkey/getminkey操作，必须都在O(1)时间内完成。</p>
<p><a href="https://leetcode.com/problems/all-oone-data-structure/description/">https://leetcode.com/problems/all-oone-data-structure/description/</a></p>
<div class="question-description">
<div>
<p>Implement a data structure supporting the following operations:</p>
<ol>
<li>Inc(Key) &#8211; Inserts a new key with value 1. Or increments an existing key by 1. Key is guaranteed to be a <b>non-empty</b> string.</li>
<li>Dec(Key) &#8211; If Key&#8217;s value is 1, remove it from the data structure. Otherwise decrements an existing key by 1. If the key does not exist, this function does nothing. Key is guaranteed to be a <b>non-empty</b> string.</li>
<li>GetMaxKey() &#8211; Returns one of the keys with maximal value. If no element exists, return an empty string <code>""</code>.</li>
<li>GetMinKey() &#8211; Returns one of the keys with minimal value. If no element exists, return an empty string <code>""</code>.</li>
</ol>
<p>Challenge: Perform all these in O(1) time complexity.</p>
</div>
<p><img class="alignnone size-full wp-image-2439" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/04/432-ep178.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/04/432-ep178.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/04/432-ep178-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/04/432-ep178-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
</div>
<h1><strong>Solution</strong></h1>
<p>Time complexity: O(1)</p>
<p>Space complexity: O(n), n = # of unique keys</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 32 ms
class AllOne {
public:
  /** Initialize your data structure here. */
  AllOne() {}

  /** Inserts a new key &lt;Key&gt; with value 1. Or increments an existing key by 1. */
  void inc(string key) {
    auto it = m_.find(key);
    
    if (it == m_.end()) {
      if (l_.empty() || l_.front().value != 1) 
        l_.push_front({1, {key}});
      else
        l_.front().keys.insert(key);
      m_[key] = l_.begin();
      return;
    }
    
    auto lit = it-&gt;second;
    
    auto nit = next(lit);
    if (nit == l_.end() || nit-&gt;value != lit-&gt;value + 1)
      nit = l_.insert(nit, {lit-&gt;value + 1, {}});
    nit-&gt;keys.insert(key);
    m_[key] = nit;
    
    remove(lit, key);
  }

  /** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */
  void dec(string key) {
    auto it = m_.find(key);
    if (it == m_.end()) return;
    
    auto lit = it-&gt;second;
        
    if (lit-&gt;value &gt; 1) {
      auto pit = prev(lit);
      if (lit == l_.begin() || pit-&gt;value != lit-&gt;value - 1)
        pit = l_.insert(lit, {lit-&gt;value - 1, {}});
      pit-&gt;keys.insert(key);
      m_[key] = pit;
    } else {
      // value == 1, remove from the data structure
      m_.erase(key);
    }
    
    remove(lit, key);    
  }

  /** Returns one of the keys with maximal value. */
  string getMaxKey() {
    return l_.empty() ? "" : *l_.back().keys.cbegin();
  }

  /** Returns one of the keys with Minimal value. */
  string getMinKey() {
    return l_.empty() ? "" : *l_.front().keys.cbegin();
  }
private:
  struct Node {  
    int value;
    unordered_set&lt;string&gt; keys;
  };
  
  list&lt;Node&gt; l_;
  unordered_map&lt;string, list&lt;Node&gt;::iterator&gt; m_;
  
  // Remove from old node.
  void remove(list&lt;Node&gt;::iterator it, const string&amp; key) {
    it-&gt;keys.erase(key);
    if (it-&gt;keys.empty())
      l_.erase(it);
  }
};</pre><p></p>
<h1><strong>Related Problems</strong></h1>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/hashtable/leetcode-460-lfu-cache/">[解题报告] LeetCode 460. LFU Cache 花花酱</a></li>
<li><a href="http://zxi.mytechroad.com/blog/hashtable/leetcode-146-lru-cache/">[解题报告] LeetCode 146. LRU Cache O(1)</a></li>
<li><a href="http://zxi.mytechroad.com/blog/hashtable/leetcode-380-insert-delete-getrandom-o1/">[解题报告] LeetCode 380. Insert Delete GetRandom O(1)</a></li>
<li><a href="http://zxi.mytechroad.com/blog/hashtable/leetcode-381-insert-delete-getrandom-o1-duplicates-allowed/">[解题报告] LeetCode 381. Insert Delete GetRandom O(1) &amp;#8211; Duplicates allowed</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/data-structure/leetcode-432-all-oone-data-structure/">花花酱 LeetCode 432. All O`one Data Structure</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/data-structure/leetcode-432-all-oone-data-structure/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 381. Insert Delete GetRandom O(1) &#8211; Duplicates allowed</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-381-insert-delete-getrandom-o1-duplicates-allowed/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-381-insert-delete-getrandom-o1-duplicates-allowed/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 17 Sep 2017 15:44:01 +0000</pubDate>
				<category><![CDATA[Data Structure]]></category>
		<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[O(1)]]></category>
		<category><![CDATA[random]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=304</guid>

					<description><![CDATA[<p>https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/description/ Problem: Design a data structure that supports all following operations in average O(1) time. Note: Duplicate elements are allowed. insert(val): Inserts an item val to the collection.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-381-insert-delete-getrandom-o1-duplicates-allowed/">花花酱 LeetCode 381. Insert Delete GetRandom O(1) &#8211; Duplicates allowed</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/mRTgft9sBhA?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p>https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/description/</p>
<p><strong>Problem:</strong></p>
<p>Design a data structure that supports all following operations in <i>average</i> <b>O(1)</b> time.</p>
<p><b>Note: Duplicate elements are allowed.</b></p>
<ol>
<li><code>insert(val)</code>: Inserts an item val to the collection.</li>
<li><code>remove(val)</code>: Removes an item val from the collection if present.</li>
<li><code>getRandom</code>: Returns a random element from current collection of elements. The probability of each element being returned is <b>linearly related</b> to the number of same value the collection contains.</li>
</ol>
<p><strong>Idea:</strong></p>
<p>Hashtable + array</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/381-ep58-1.png"><img class="alignnone size-full wp-image-309" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/381-ep58-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/381-ep58-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/381-ep58-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/381-ep58-1-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/381-ep58-1-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a> <a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/381-ep58-2.png"><img class="alignnone size-full wp-image-308" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/381-ep58-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/381-ep58-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/381-ep58-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/381-ep58-2-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/381-ep58-2-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a><a style="font-size: 1rem; color: #0f3647;" href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/381-ep58-3.png"><img class="alignnone size-full wp-image-307" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/381-ep58-3.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/381-ep58-3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/381-ep58-3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/381-ep58-3-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/381-ep58-3-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p><strong style="font-size: 1rem;">Solution:</strong></p>
<p>&nbsp;</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 49 ms
class RandomizedCollection {
public:
    /** Initialize your data structure here. */
    RandomizedCollection() {}
    
    /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
    bool insert(int val) {        
        m_[val].push_back(vals_.size());
        vals_.emplace_back(val, m_[val].size() - 1);
        return m_[val].size() == 1u;
    }
    
    /** Removes a value from the collection. Returns true if the collection contained the specified element. */
    bool remove(int val) {
        if (!m_.count(val)) return false;
        int index_to_evict = m_[val].back();
        const auto&amp; last_entry = vals_.back();
        
        // Update index
        m_[last_entry.first][last_entry.second] = index_to_evict;
        
        // Swap vals
        swap(vals_.back(), vals_[index_to_evict]);
        
        // Clenup
        vals_.pop_back();        
        m_[val].pop_back();
        if (m_[val].empty()) m_.erase(val);
        
        return true;
    }
    
    /** Get a random element from the collection. */
    int getRandom() {
        return vals_[rand() % vals_.size()].first;
    }
private:
    // val -&gt; indices array: indices in vals_
    unordered_map&lt;int, vector&lt;int&gt;&gt; m_;
    // {val, index in the indices array}
    vector&lt;pair&lt;int,int&gt;&gt; vals_;
};</pre><p>Java</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 122 ms (&lt;94.53%)
class RandomizedCollection {
  class Entry {
    public int value;
    public int index;
    public Entry(int val, int idx) {
      value = val;
      index = idx;
    }
  }
  
  private Map&lt;Integer, List&lt;Integer&gt;&gt; m;
  private List&lt;Entry&gt; vals;
  private Random rand;

  /** Initialize your data structure here. */
  public RandomizedCollection() {
    m = new HashMap&lt;&gt;();
    vals = new ArrayList&lt;&gt;();
    rand = new Random();
  }

  /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
  public boolean insert(int val) {    
    List&lt;Integer&gt; l = m.getOrDefault(val, new ArrayList&lt;Integer&gt;());
    l.add(vals.size());
    m.put(val, l);
    vals.add(new Entry(val, l.size() - 1));
    return l.size() == 1;
  }

  /** Removes a value from the collection. Returns true if the collection contained the specified element. */
  public boolean remove(int val) {    
    if (!m.containsKey(val)) return false;
    List&lt;Integer&gt; l = m.get(val);
    int index_to_evict = l.get(l.size() - 1);
    Entry last_entry = vals.get(vals.size() - 1);

    // Update index
    m.get(last_entry.value).set(last_entry.index, index_to_evict);

    // Swap vals
    vals.set(index_to_evict, last_entry);    

    // Cleanup
    vals.remove(vals.size() - 1);
    l.remove(l.size() - 1);
    if (l.size() == 0) m.remove(val);

    return true;
  }

  /** Get a random element from the collection. */
  public int getRandom() {    
    return vals.get(rand.nextInt(vals.size())).value;
  }
}</pre><p>&nbsp;</p>
<p><strong>Related Problems:</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/hashtable/leetcode-380-insert-delete-getrandom-o1/">[解题报告] LeetCode 380. Insert Delete GetRandom O(1)</a></li>
<li><a href="http://zxi.mytechroad.com/blog/hashtable/leetcode-460-lfu-cache/">[解题报告] LeetCode 460. LFU Cache O(1)</a></li>
<li><a href="http://zxi.mytechroad.com/blog/hashtable/leetcode-146-lru-cache/">[解题报告] LeetCode 146. LRU Cache O(1)</a></li>
<li><a href="http://zxi.mytechroad.com/blog/leetcode/leetcode-295-find-median-from-data-stream/">[解题报告] LeetCode 295. Find Median from Data Stream O(logn) + O(1)</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-381-insert-delete-getrandom-o1-duplicates-allowed/">花花酱 LeetCode 381. Insert Delete GetRandom O(1) &#8211; Duplicates allowed</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/hashtable/leetcode-381-insert-delete-getrandom-o1-duplicates-allowed/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 380. Insert Delete GetRandom O(1)</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-380-insert-delete-getrandom-o1/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-380-insert-delete-getrandom-o1/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 17 Sep 2017 06:44:34 +0000</pubDate>
				<category><![CDATA[Data Structure]]></category>
		<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[O(1)]]></category>
		<category><![CDATA[random]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=296</guid>

					<description><![CDATA[<p>Problem: Design a data structure that supports all following operations in average O(1) time. insert(val): Inserts an item val to the set if not already present. remove(val): Removes&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-380-insert-delete-getrandom-o1/">花花酱 LeetCode 380. Insert Delete GetRandom O(1)</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/y240Qh9H9uk?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p><strong>Problem:</strong></p>
<p>Design a data structure that supports all following operations in <i>average</i> <b>O(1)</b> time.</p>
<ol>
<li><code>insert(val)</code>: Inserts an item val to the set if not already present.</li>
<li><code>remove(val)</code>: Removes an item val from the set if present.</li>
<li><code>getRandom</code>: Returns a random element from current set of elements. Each element must have the <b>same probability</b> of being returned.</li>
</ol>
<p>&nbsp;</p>
<p><strong>Idea:</strong></p>
<p>Hashtable + array</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/380-ep57-1.png"><img class="alignnone size-full wp-image-302" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/380-ep57-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/380-ep57-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/380-ep57-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/380-ep57-1-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/380-ep57-1-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/380-ep57-2.png"><img class="alignnone size-full wp-image-301" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/380-ep57-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/380-ep57-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/380-ep57-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/380-ep57-2-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/380-ep57-2-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/380-ep57-3.png"><img class="alignnone size-full wp-image-300" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/380-ep57-3.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/380-ep57-3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/380-ep57-3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/380-ep57-3-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/380-ep57-3-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p><strong>Time complexity:</strong></p>
<p>O(1)</p>
<p>&nbsp;</p>
<p><strong>Solution:</strong></p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 49 ms
class RandomizedSet {
public:
    /** Initialize your data structure here. */
    RandomizedSet() {}
    
    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    bool insert(int val) {
        if(m_.count(val)) return false;
        m_[val] = vals_.size();
        vals_.push_back(val);
        return true;
    }
    
    /** Removes a value from the set. Returns true if the set contained the specified element. */
    bool remove(int val) {
        if(!m_.count(val)) return false;
        int index = m_[val];
        m_[vals_.back()] = index;
        m_.erase(val);
        std::swap(vals_[index], vals_.back());
        vals_.pop_back();
        return true;
    }
    
    /** Get a random element from the set. */
    int getRandom() {
        int index = rand() % vals_.size();
        return vals_[index];
    }
private:
    // val -&gt; index in the array
    unordered_map&lt;int, int&gt; m_;
    vector&lt;int&gt; vals_;
};</pre><p>&nbsp;</p>
<p><strong>Related Problems:</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/hashtable/leetcode-381-insert-delete-getrandom-o1-duplicates-allowed/">LeetCode 381. Insert Delete GetRandom O(1) &amp;#8211; Duplicates allowed</a></li>
<li><a href="http://zxi.mytechroad.com/blog/hashtable/leetcode-460-lfu-cache/">[解题报告] LeetCode 460. LFU Cache O(1)</a></li>
<li><a href="http://zxi.mytechroad.com/blog/hashtable/leetcode-146-lru-cache/">[解题报告] LeetCode 146. LRU Cache O(1)</a></li>
<li><a href="http://zxi.mytechroad.com/blog/leetcode/leetcode-295-find-median-from-data-stream/">[解题报告] LeetCode 295. Find Median from Data Stream O(logn) + O(1)</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-380-insert-delete-getrandom-o1/">花花酱 LeetCode 380. Insert Delete GetRandom O(1)</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/hashtable/leetcode-380-insert-delete-getrandom-o1/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
