<?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>random Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/random/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/random/</link>
	<description></description>
	<lastBuildDate>Mon, 30 Sep 2019 03:37:37 +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>random Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/random/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 528. Random Pick with Weight</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-528-random-pick-with-weight/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-528-random-pick-with-weight/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 30 Sep 2019 03:34:54 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[random]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5613</guid>

					<description><![CDATA[<p>Given an array&#160;w&#160;of positive integers, where&#160;w[i]&#160;describes the weight of index&#160;i,&#160;write a function&#160;pickIndex&#160;which randomly&#160;picks an index&#160;in proportion&#160;to its weight. Note: 1 &#60;= w.length &#60;= 10000 1&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-528-random-pick-with-weight/">花花酱 LeetCode 528. Random Pick with Weight</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 array&nbsp;<code>w</code>&nbsp;of positive integers, where&nbsp;<code>w[i]</code>&nbsp;describes the weight of index&nbsp;<code>i</code>,&nbsp;write a function&nbsp;<code>pickIndex</code>&nbsp;which randomly&nbsp;picks an index&nbsp;in proportion&nbsp;to its weight.</p>



<p>Note:</p>



<ol><li><code>1 &lt;= w.length &lt;= 10000</code></li><li><code>1 &lt;= w[i] &lt;= 10^5</code></li><li><code>pickIndex</code>&nbsp;will be called at most&nbsp;<code>10000</code>&nbsp;times.</li></ol>



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



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



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



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



<p><strong>Explanation of Input Syntax:</strong></p>



<p>The input is two lists:&nbsp;the subroutines called&nbsp;and their&nbsp;arguments.&nbsp;<code>Solution</code>&#8216;s&nbsp;constructor has one argument, the&nbsp;array&nbsp;<code>w</code>.&nbsp;<code>pickIndex</code>&nbsp;has no arguments.&nbsp;Arguments&nbsp;are&nbsp;always wrapped with a list, even if there aren&#8217;t any.</p>



<h2><strong>Solution: Binary Search</strong></h2>



<p>Crate a cumulative weight array, random sample a &#8220;weight&#8221;, do a binary search to see which bucket that weight falls in.<br>e.g. w = [2, 3, 1, 4], sum = [2, 5, 6, 10]<br>sample 3 =&gt; index = 1<br>sample 7 =&gt; index = 3</p>



<p>Time complexity: Init: O(n) Pick: O(logn)<br>Space complexity: O(n)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  Solution(vector&lt;int&gt; w): sums_(std::move(w)) {
    partial_sum(begin(sums_), end(sums_), begin(sums_));    
  }

  int pickIndex() {
    int s = rand() % sums_.back();
    return upper_bound(begin(sums_), end(sums_), s) - begin(sums_);
  }
private:  
  vector&lt;int&gt; sums_;
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-528-random-pick-with-weight/">花花酱 LeetCode 528. Random Pick with Weight</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/leetcode-528-random-pick-with-weight/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 961. N-Repeated Element in Size 2N Array</title>
		<link>https://zxi.mytechroad.com/blog/randomization/leetcode-961-n-repeated-element-in-size-2n-array/</link>
					<comments>https://zxi.mytechroad.com/blog/randomization/leetcode-961-n-repeated-element-in-size-2n-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 23 Dec 2018 08:41:29 +0000</pubDate>
				<category><![CDATA[Randomization]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[random]]></category>
		<category><![CDATA[repeat]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4533</guid>

					<description><![CDATA[<p>In a array&#160;A&#160;of size&#160;2N, there are&#160;N+1&#160;unique elements, and exactly one of these elements is repeated N times. Return the element repeated&#160;N&#160;times. Example 1: Input: [1,2,3,3]Output:&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/randomization/leetcode-961-n-repeated-element-in-size-2n-array/">花花酱 LeetCode 961. N-Repeated Element in Size 2N Array</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>In a array&nbsp;<code>A</code>&nbsp;of size&nbsp;<code>2N</code>, there are&nbsp;<code>N+1</code>&nbsp;unique elements, and exactly one of these elements is repeated N times.</p>



<p>Return the element repeated&nbsp;<code>N</code>&nbsp;times.</p>



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



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



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



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



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



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



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



<ol><li><code>4 &lt;= A.length &lt;= 10000</code></li><li><code>0 &lt;= A[i] &lt; 10000</code></li><li><code>A.length</code>&nbsp;is even</li></ol>



<h1><strong>Solution: Randomization</strong></h1>



<p>Randomly pick two numbers in the array, if they are the same (25% probability) return the number, do it until the two numbers are the same.</p>



<p>Time complexity: O(1) expected 4<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, running time: 72 ms
class Solution {
public:
  int repeatedNTimes(vector&lt;int&gt;&amp; A) {
    int i = 0;
    int j = 0;
    while (i == j || A[i] != A[j]) {
      i = rand() % A.size();
      j = rand() % A.size();
    }
    return A[i];
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/randomization/leetcode-961-n-repeated-element-in-size-2n-array/">花花酱 LeetCode 961. N-Repeated Element in Size 2N Array</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/randomization/leetcode-961-n-repeated-element-in-size-2n-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 881. Random Flip Matrix</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-881-random-flip-matrix/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-881-random-flip-matrix/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 31 Jul 2018 15:33:05 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[random]]></category>
		<category><![CDATA[sample]]></category>
		<category><![CDATA[shuffle]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3398</guid>

					<description><![CDATA[<p>Problem You are given the number of rows n_rows and number of columns n_cols of a 2D binary matrix where all values are initially 0. Write a function flip which chooses a 0 value uniformly at random, changes&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-881-random-flip-matrix/">花花酱 LeetCode 881. Random Flip Matrix</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>You are given the number of rows <code>n_rows</code> and number of columns <code>n_cols</code> of a 2D binary matrix where all values are initially 0. Write a function <code>flip</code> which chooses a 0 value <a href="https://en.wikipedia.org/wiki/Discrete_uniform_distribution" target="_blank" rel="noopener">uniformly at random</a>, changes it to 1, and then returns the position <code>[row.id, col.id]</code> of that value. Also, write a function <code>reset</code> which sets all values back to 0. <strong>Try to minimize the number of calls to system&#8217;s Math.random()</strong> and optimize the time and space complexity.</p>
<p>Note:</p>
<ol>
<li><code>1 &lt;= n_rows, n_cols &lt;= 10000</code></li>
<li><code>0 &lt;= row.id &lt; n_rows</code> and <code>0 &lt;= col.id &lt; n_cols</code></li>
<li><code>flip</code> will not be called when the matrix has no 0 values left.</li>
<li>the total number of calls to <code>flip</code> and <code>reset</code> will not exceed 1000.</li>
</ol>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: 
</strong><span id="example-input-1-1">["Solution","flip","flip","flip","flip"]
</span><span id="example-input-1-2">[[2,3],[],[],[],[]]</span>
<strong>Output: </strong><span id="example-output-1">[null,[0,1],[1,2],[1,0],[1,1]]</span>
</pre>
<div>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false "><strong>Input: 
</strong><span id="example-input-2-1">["Solution","flip","flip","reset","flip"]
</span><span id="example-input-2-2">[[1,2],[],[],[],[]]</span>
<strong>Output: </strong><span id="example-output-2">[null,[0,0],[0,1],null,[0,0]]</span></pre>
</div>
<p><strong>Explanation of Input Syntax:</strong></p>
<p>The input is two lists: the subroutines called and their arguments. <code>Solution</code>&#8216;s constructor has two arguments, <code>n_rows</code> and <code>n_cols</code>. <code>flip</code> and <code>reset</code> have no arguments. Arguments are always wrapped with a list, even if there aren&#8217;t any.</p>
<h1><strong>Solution 1: Hashtable + Resample</strong></h1>
<p>Time complexity: O(|flip|) = O(1000) = O(1)</p>
<p>Space complexity: O(|flip|) = O(1000) = O(1)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 12 ms
class Solution {
public:
  Solution(int n_rows, int n_cols): 
    rows_(n_rows), cols_(n_cols), n_(rows_ * cols_) {}

  vector&lt;int&gt; flip() {
    int index = rand() % n_;
    while (m_.count(index))
      index = rand() % n_;    
    m_.insert(index);
    return {index / cols_, index % cols_};
  }

  void reset() {
    m_.clear();
    n_ = rows_ * cols_;
  }
private:
  const int rows_;
  const int cols_;
  int n_;
  unordered_set&lt;int&gt; m_;
};</pre><p></p>
<h1><strong>Solution 2: </strong><a href="https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle">Fisher–Yates shuffle</a></h1>
<p>Generate a random shuffle of 0 to n &#8211; 1, one number at a time.</p>
<p>Time complexity: flip: O(1)</p>
<p>Space complexity: O(|flip|) = O(1000) = O(1)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 12 ms
class Solution {
public:
  Solution(int n_rows, int n_cols): 
    rows_(n_rows), cols_(n_cols), n_(rows_ * cols_) {}

  vector&lt;int&gt; flip() {
    int s = rand() % (n_--);
    int index = s;
    if (m_.count(s))
      index = m_[s];
    m_[s] = m_.count(n_) ? m_[n_] : n_;
    return {index / cols_, index % cols_};
  }

  void reset() {
    m_.clear();
    n_ = rows_ * cols_;
  }
private:
  const int rows_;
  const int cols_;
  int n_;
  unordered_map&lt;int, int&gt; m_;
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-881-random-flip-matrix/">花花酱 LeetCode 881. Random Flip Matrix</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-881-random-flip-matrix/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 882. Random Point in Non-overlapping Rectangles</title>
		<link>https://zxi.mytechroad.com/blog/geometry/leetcode-882-random-point-in-non-overlapping-rectangles/</link>
					<comments>https://zxi.mytechroad.com/blog/geometry/leetcode-882-random-point-in-non-overlapping-rectangles/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 29 Jul 2018 00:45:20 +0000</pubDate>
				<category><![CDATA[Geometry]]></category>
		<category><![CDATA[geometry]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[pick]]></category>
		<category><![CDATA[random]]></category>
		<category><![CDATA[weighted]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3342</guid>

					<description><![CDATA[<p>Problem Given a list of non-overlapping axis-aligned rectangles rects, write a function pick which randomly and uniformily picks an integer point in the space covered by the rectangles. Note: An integer point is a point&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/geometry/leetcode-882-random-point-in-non-overlapping-rectangles/">花花酱 LeetCode 882. Random Point in Non-overlapping Rectangles</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 list of <strong>non-overlapping</strong> axis-aligned rectangles <code>rects</code>, write a function <code>pick</code> which randomly and uniformily picks an <strong>integer point</strong> in the space covered by the rectangles.</p>
<p>Note:</p>
<ol>
<li>An <strong>integer point</strong> is a point that has integer coordinates.</li>
<li>A point on the perimeter of a rectangle is <strong>included</strong> in the space covered by the rectangles.</li>
<li><code>i</code>th rectangle = <code>rects[i]</code> = <code>[x1,y1,x2,y2]</code>, where <code>[x1, y1]</code> are the integer coordinates of the bottom-left corner, and <code>[x2, y2]</code> are the integer coordinates of the top-right corner.</li>
<li>length and width of each rectangle does not exceed <code>2000</code>.</li>
<li><code>1 &lt;= rects.length &lt;= 100</code></li>
<li><code>pick</code> return a point as an array of integer coordinates <code>[p_x, p_y]</code></li>
<li><code>pick</code> is called at most <code>10000</code> times.</li>
</ol>
<div>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: 
</strong><span id="example-input-1-1">["Solution","pick","pick","pick"]
</span><span id="example-input-1-2">[[[[1,1,5,5]]],[],[],[]]</span>
<strong>Output: 
</strong><span id="example-output-1">[null,[4,1],[4,1],[3,3]]</span>
</pre>
<div>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false "><strong>Input: 
</strong><span id="example-input-2-1">["Solution","pick","pick","pick","pick","pick"]
</span><span id="example-input-2-2">[[[[-2,-2,-1,-1],[1,0,3,0]]],[],[],[],[],[]]</span>
<strong>Output: 
</strong><span id="example-output-2">[null,[-1,-2],[2,0],[-2,-1],[3,0],[-2,-2]]</span></pre>
</div>
<div>
<p><strong>Explanation of Input Syntax:</strong></p>
<p>The input is two lists: the subroutines called and their arguments. <code>Solution</code>&#8216;s constructor has one argument, the array of rectangles <code>rects</code>. <code>pick</code> has no arguments. Arguments are always wrapped with a list, even if there aren&#8217;t any.</p>
</div>
<h1><strong>Solution: Binary Search</strong></h1>
<p>Same as <a href="http://zxi.mytechroad.com/blog/math/leetcode-880-random-pick-with-weight/">LeetCode 880. Random Pick with Weight</a></p>
<p>Use area of the rectangles as weights.</p>
<p>Time complexity: Init: O(n) Pick: O(logn)</p>
<p>Space complexity: O(n)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 92 ms
class Solution {
public:
  Solution(vector&lt;vector&lt;int&gt;&gt; rects): rects_(std::move(rects)) {
    sums_ = vector&lt;int&gt;(rects_.size());
    for (int i = 0; i &lt; rects_.size(); ++i) {
      sums_[i] = (rects_[i][2] - rects_[i][0] + 1) * (rects_[i][3] - rects_[i][1] + 1);
      if (i &gt; 0) sums_[i] += sums_[i - 1];
    }
  }

  vector&lt;int&gt; pick() {
    const int s = nextInt(sums_.back()) + 1;
    int index = lower_bound(sums_.begin(), sums_.end(), s) - sums_.begin();
    const auto&amp; rect = rects_[index];
    return {rect[0] + nextInt(rect[2] - rect[0] + 1),
            rect[1] + nextInt(rect[3] - rect[1] + 1)};
  }
    
private:  
  vector&lt;int&gt; sums_;
  vector&lt;vector&lt;int&gt;&gt; rects_;
  
  // Returns a random int in [0, n - 1]
  int nextInt(int n) {
    return rand() / static_cast&lt;double&gt;(RAND_MAX) * n;
  }
};</pre><p></p>
<h1><strong>Related Problems</strong></h1>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/math/leetcode-880-random-pick-with-weight/">花花酱 LeetCode 880. Random Pick with Weight</a></li>
</ul>
</div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/geometry/leetcode-882-random-point-in-non-overlapping-rectangles/">花花酱 LeetCode 882. Random Point in Non-overlapping Rectangles</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/geometry/leetcode-882-random-point-in-non-overlapping-rectangles/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 880. Random Pick with Weight</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-880-random-pick-with-weight/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-880-random-pick-with-weight/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 29 Jul 2018 00:08:09 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[CDF]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[PDF]]></category>
		<category><![CDATA[pick]]></category>
		<category><![CDATA[random]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3339</guid>

					<description><![CDATA[<p>Problem Given an array w of positive integers, where w[i] describes the weight of index i, write a function pickIndex which randomly picks an index in proportion to its weight. Note: 1 &#60;= w.length &#60;= 10000&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-880-random-pick-with-weight/">花花酱 LeetCode 880. Random Pick with Weight</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 an array <code>w</code> of positive integers, where <code>w[i]</code> describes the weight of index <code>i</code>, write a function <code>pickIndex</code> which randomly picks an index in proportion to its weight.</p>
<p>Note:</p>
<ol>
<li><code>1 &lt;= w.length &lt;= 10000</code></li>
<li><code>1 &lt;= w[i] &lt;= 10^5</code></li>
<li><code>pickIndex</code> will be called at most <code>10000</code> times.</li>
</ol>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: 
</strong><span id="example-input-1-1">["Solution","pickIndex"]
</span><span id="example-input-1-2">[[[1]],[]]</span>
<strong>Output: </strong><span id="example-output-1">[null,0]</span>
</pre>
<div>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false "><strong>Input: 
</strong><span id="example-input-2-1">["Solution","pickIndex","pickIndex","pickIndex","pickIndex","pickIndex"]
</span><span id="example-input-2-2">[[[1,3]],[],[],[],[],[]]</span>
<strong>Output: </strong><span id="example-output-2">[null,0,1,1,1,0]</span></pre>
</div>
<p><strong>Explanation of Input Syntax:</strong></p>
<p>The input is two lists: the subroutines called and their arguments. <code>Solution</code>&#8216;s constructor has one argument, the array <code>w</code>. <code>pickIndex</code> has no arguments. Arguments are always wrapped with a list, even if there aren&#8217;t any.</p>
<h1><strong>Solution: Binary Search</strong></h1>
<ol>
<li>Convert PDF to CDF</li>
<li>Uniformly sample a value s in [1, sum(weights)].</li>
<li>Use binary search to find first index such that PDF[index] &gt;= s.</li>
</ol>
<p>Time complexity: Init O(n), query O(logn)</p>
<p>Space complexity: O(n)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 184 ms
class Solution {
public:
  Solution(vector&lt;int&gt; w) { 
    sums_ = std::move(w);
    for (int i = 1; i &lt; sums_.size(); ++i)
      sums_[i] += sums_[i - 1];
  }

  int pickIndex() {
    int s = rand() / static_cast&lt;double&gt;(RAND_MAX) * sums_.back() + 1;
    return lower_bound(sums_.begin(), sums_.end(), s) - sums_.begin();
    // or
    // int l = 0;
    // int r = sums_.size();
    // while (l &lt; r) {
    //   int m = (r - l) / 2 + l;
    //   if (sums_[m] &lt; s)
    //     l = m + 1;
    //   else
    //     r = m;
    // }
    // return l;
  }
private:  
  vector&lt;int&gt; sums_;
};</pre><p></p>
<h1><strong>Related Problems</strong></h1>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/geometry/leetcode-882-random-point-in-non-overlapping-rectangles/">花花酱 LeetCode 882. Random Point in Non-overlapping Rectangles</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-880-random-pick-with-weight/">花花酱 LeetCode 880. Random Pick with Weight</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/leetcode-880-random-pick-with-weight/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 883. Generate Random Point in a Circle</title>
		<link>https://zxi.mytechroad.com/blog/geometry/leetcode-883-generate-random-point-in-a-circle/</link>
					<comments>https://zxi.mytechroad.com/blog/geometry/leetcode-883-generate-random-point-in-a-circle/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 28 Jul 2018 23:50:28 +0000</pubDate>
				<category><![CDATA[Geometry]]></category>
		<category><![CDATA[geometry]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[polar]]></category>
		<category><![CDATA[random]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3336</guid>

					<description><![CDATA[<p>Problem Given the radius and x-y positions of the center of a circle, write a function randPoint which generates a uniform random point in the circle. Note: input and&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/geometry/leetcode-883-generate-random-point-in-a-circle/">花花酱 LeetCode 883. Generate Random Point in a Circle</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 the radius and x-y positions of the center of a circle, write a function <code>randPoint</code> which generates a uniform random point in the circle.</p>
<p>Note:</p>
<ol>
<li>input and output values are in <a href="https://www.webopedia.com/TERM/F/floating_point_number.html" target="_blank" rel="noopener">floating-point</a>.</li>
<li>radius and x-y position of the center of the circle is passed into the class constructor.</li>
<li>a point on the circumference of the circle is considered to be in the circle.</li>
<li><code>randPoint</code> returns a size 2 array containing x-position and y-position of the random point, in that order.</li>
</ol>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: 
</strong><span id="example-input-1-1">["Solution","randPoint","randPoint","randPoint"]
</span><span id="example-input-1-2">[[1,0,0],[],[],[]]</span>
<strong>Output: </strong><span id="example-output-1">[null,[-0.72939,-0.65505],[-0.78502,-0.28626],[-0.83119,-0.19803]]</span>
</pre>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input: 
</strong><span id="example-input-2-1">["Solution","randPoint","randPoint","randPoint"]
</span><span id="example-input-2-2">[[10,5,-7.5],[],[],[]]</span>
<strong>Output: </strong><span id="example-output-2">[null,[11.52438,-8.33273],[2.46992,-16.21705],[11.13430,-12.42337]]</span></pre>
<p><strong>Explanation of Input Syntax:</strong></p>
<p>The input is two lists: the subroutines called and their arguments. <code>Solution</code>&#8216;s constructor has three arguments, the radius, x-position of the center, and y-position of the center of the circle. <code>randPoint</code> has no arguments. Arguments are always wrapped with a list, even if there aren&#8217;t any.</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></p>
<h1>Solution: Polar Coordinate</h1>
<p>uniform sample an angle a: [0, 2*Pi)</p>
<p>uniform sample a radius r: [0, 1)</p>
<p>Number of random points in a cycle should be proportional to the square of distance to the center.</p>
<p>e.g. there are 4 times of points with distance d than points with distance d/2.</p>
<p>Thus sqrt(r) is uniformly distributed.</p>
<p>r&#8217; = sqrt(r),</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 116 ms
class Solution {
public:
  Solution(double radius, double x_center, double y_center)
    :r_(radius), x_(x_center), y_(y_center) {}

  vector&lt;double&gt; randPoint() {
    double a = rand() / static_cast&lt;double&gt;(RAND_MAX) * 2 * M_PI;
    double r = sqrt(rand() / static_cast&lt;double&gt;(RAND_MAX)) * r_;
    return {x_ + r * cos(a), y_ + r * sin(a)};
  }
private:
  double r_;
  double x_;
  double y_;
};</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/geometry/leetcode-883-generate-random-point-in-a-circle/">花花酱 LeetCode 883. Generate Random Point in a Circle</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/geometry/leetcode-883-generate-random-point-in-a-circle/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 872. Implement Rand10() Using Rand7()</title>
		<link>https://zxi.mytechroad.com/blog/desgin/leetcode-872-implement-rand10-using-rand7/</link>
					<comments>https://zxi.mytechroad.com/blog/desgin/leetcode-872-implement-rand10-using-rand7/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 16 Jul 2018 16:08:23 +0000</pubDate>
				<category><![CDATA[Desgin]]></category>
		<category><![CDATA[desgin]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[random]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3199</guid>

					<description><![CDATA[<p>Problem Given a function rand7 which generates a uniform random integer in the range 1 to 7, write a function rand10 which generates a uniform random integer in the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/desgin/leetcode-872-implement-rand10-using-rand7/">花花酱 LeetCode 872. Implement Rand10() Using Rand7()</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 function <code>rand7</code> which generates a uniform random integer in the range 1 to 7, write a function <code>rand10</code> which generates a uniform random integer in the range 1 to 10.</p>
<p>Do NOT use system&#8217;s <code>Math.random()</code>.</p>
<div>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-1-1">1</span>
<strong>Output: </strong><span id="example-output-1">[7]</span>
</pre>
<div>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-2-1">2</span>
<strong>Output: </strong><span id="example-output-2">[8,4]</span>
</pre>
<div>
<p><strong>Example 3:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-3-1">3</span>
<strong>Output: </strong><span id="example-output-3">[8,1,10]</span>
</pre>
<p><strong>Note:</strong></p>
<ol>
<li><code>rand7</code> is predefined.</li>
<li>Each testcase has one argument: <code>n</code>, the number of times that <code>rand10</code> is called.</li>
</ol>
<h1><strong>Solution: Math</strong></h1>
<p>Time complexity: O(49/40) = O(1)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 112 ms
class Solution {
public:
  int rand10() {
    int target = 40;
    while (target &gt;= 40)
      target = 7 * (rand7() - 1) + (rand7() - 1);
    return target % 10 + 1;
  }
};</pre><p>Time complexity: O(7/6 + 7 / 5) = O(1)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 112 ms
class Solution {
public:
  int rand10() {
    int i = INT_MAX;
    int j = INT_MAX;
    while (i &gt; 6) i = rand7(); // i = [1, 2, 3, 4, 5, 6]
    while (j &gt; 5) j = rand7(); // j = [1, 2, 3, 4, 5]
    return j + 5 * (i &amp; 1);
  }
};</pre><p>&nbsp;</p>
</div>
</div>
</div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/desgin/leetcode-872-implement-rand10-using-rand7/">花花酱 LeetCode 872. Implement Rand10() Using Rand7()</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/desgin/leetcode-872-implement-rand10-using-rand7/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 382. Linked List Random Node</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-382-linked-list-random-node/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-382-linked-list-random-node/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 17 Mar 2018 08:00:39 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[random]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2151</guid>

					<description><![CDATA[<p>题目大意：写一个方法返回列表中的随机元素。 Problem: https://leetcode.com/problems/linked-list-random-node/description/ Given a singly linked list, return a random node&#8217;s value from the linked list. Each node must have the same probability of being chosen.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-382-linked-list-random-node/">花花酱 LeetCode 382. Linked List Random Node</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>题目大意：写一个方法返回列表中的随机元素。</p>
<h1>Problem:</h1>
<p><a href="https://leetcode.com/problems/linked-list-random-node/description/">https://leetcode.com/problems/linked-list-random-node/description/</a></p>
<p>Given a singly linked list, return a random node&#8217;s value from the linked list. Each node must have the <b>same probability</b> of being chosen.</p>
<p><b>Follow up:</b><br />
What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?</p>
<p><b>Example:</b></p><pre class="crayon-plain-tag">// Init a singly linked list [1,2,3].
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
Solution solution = new Solution(head);

// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
solution.getRandom();</pre><p></p>
<h1>Solution:</h1>
<p>C++</p>
<p>Time Complexity: O(n)</p>
<p>Space Complexity: O(1)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 43 ms
class Solution {
public:
  /** @param head The linked list's head.
      Note that the head is guaranteed to be not null, so it contains at least one node. */
  Solution(ListNode* head) {
    head_ = head;
    
    n_ = 0;
    ListNode* curr = head;
    while (curr != nullptr) {
      curr = curr-&gt;next;
      ++n_;
    }
  }

  /** Returns a random node's value. */
  int getRandom() {
    int n = rand() % n_;
    ListNode* curr = head_;
    while (n--&gt;0)
      curr = curr-&gt;next;      
    
    return curr-&gt;val;
  }
private:
  int n_;
  
   // Does not own the object
  ListNode* head_;
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-382-linked-list-random-node/">花花酱 LeetCode 382. Linked List Random Node</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/list/leetcode-382-linked-list-random-node/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>
