<?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>set Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/set/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/set/</link>
	<description></description>
	<lastBuildDate>Sun, 17 Apr 2022 21:19:36 +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>set Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/set/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2242. Maximum Score of a Node Sequence</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-2242-maximum-score-of-a-node-sequence/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-2242-maximum-score-of-a-node-sequence/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 17 Apr 2022 06:16:40 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[set]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9662</guid>

					<description><![CDATA[<p>There is an&#160;undirected&#160;graph with&#160;n&#160;nodes, numbered from&#160;0&#160;to&#160;n - 1. You are given a&#160;0-indexed&#160;integer array&#160;scores&#160;of length&#160;n&#160;where&#160;scores[i]&#160;denotes the score of node&#160;i. You are also given a 2D integer&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-2242-maximum-score-of-a-node-sequence/">花花酱 LeetCode 2242. Maximum Score of a Node Sequence</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>There is an&nbsp;<strong>undirected</strong>&nbsp;graph with&nbsp;<code>n</code>&nbsp;nodes, numbered from&nbsp;<code>0</code>&nbsp;to&nbsp;<code>n - 1</code>.</p>



<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>scores</code>&nbsp;of length&nbsp;<code>n</code>&nbsp;where&nbsp;<code>scores[i]</code>&nbsp;denotes the score of node&nbsp;<code>i</code>. You are also given a 2D integer array&nbsp;<code>edges</code>&nbsp;where&nbsp;<code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code>&nbsp;denotes that there exists an&nbsp;<strong>undirected</strong>&nbsp;edge connecting nodes&nbsp;<code>a<sub>i</sub></code>&nbsp;and&nbsp;<code>b<sub>i</sub></code>.</p>



<p>A node sequence is&nbsp;<strong>valid</strong>&nbsp;if it meets the following conditions:</p>



<ul><li>There is an edge connecting every pair of&nbsp;<strong>adjacent</strong>&nbsp;nodes in the sequence.</li><li>No node appears more than once in the sequence.</li></ul>



<p>The score of a node sequence is defined as the&nbsp;<strong>sum</strong>&nbsp;of the scores of the nodes in the sequence.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>maximum score</strong>&nbsp;of a valid node sequence with a length of&nbsp;</em><code>4</code><em>.&nbsp;</em>If no such sequence exists, return<em>&nbsp;</em><code>-1</code>.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2022/04/15/ex1new3.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> scores = [5,2,9,8,4], edges = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]]
<strong>Output:</strong> 24
<strong>Explanation:</strong> The figure above shows the graph and the chosen node sequence [0,1,2,3].
The score of the node sequence is 5 + 2 + 9 + 8 = 24.
It can be shown that no other node sequence has a score of more than 24.
Note that the sequences [3,1,2,0] and [1,0,2,3] are also valid and have a score of 24.
The sequence [0,3,2,4] is not valid since no edge connects nodes 0 and 3.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2022/03/17/ex2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> scores = [9,20,6,4,11,12], edges = [[0,3],[5,3],[2,4],[1,3]]
<strong>Output:</strong> -1
<strong>Explanation:</strong> The figure above shows the graph.
There are no valid node sequences of length 4, so we return -1.
</pre>



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



<ul><li><code>n == scores.length</code></li><li><code>4 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li><li><code>1 &lt;= scores[i] &lt;= 10<sup>8</sup></code></li><li><code>0 &lt;= edges.length &lt;= 5 * 10<sup>4</sup></code></li><li><code>edges[i].length == 2</code></li><li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub>&nbsp;&lt;= n - 1</code></li><li><code>a<sub>i</sub>&nbsp;!= b<sub>i</sub></code></li><li>There are no duplicate edges.</li></ul>



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



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-1.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-1.png" alt="" class="wp-image-9667" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-2.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-2.png" alt="" class="wp-image-9668" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-3.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-3.png" alt="" class="wp-image-9669" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-3-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-4.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-4.png" alt="" class="wp-image-9671" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-4.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-4-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-4-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-5.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-5.png" alt="" class="wp-image-9673" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-5.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-5-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-5-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<p>Since |E| is already 5*10<sup>4</sup>, we can&#8217;t enumerate all possible sequences. We must do in O(|E|) or O(|E|log|E|).</p>



<p>Enumerate all the edges, we have a pair of node a, b. To get the optimal answer, we just need to find the largest neighbor of a and b, which we call c, d respectively. Just need to make sure a, b, c, d are unique. i.e. c != d, c != b and d != a. Since the a&#8217;s largest neighbor can be either b or d. We can&#8217;t just store the largest neighbor, but top 3 instead for each node to avoid duplications.</p>



<p>Time complexity: O(|E|*9)<br>Space complexity: O(|V|*3)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int maximumScore(vector&lt;int&gt;&amp; scores, vector&lt;vector&lt;int&gt;&gt;&amp; edges) {
    const int n = scores.size();
    vector&lt;set&lt;pair&lt;int, int&gt;&gt;&gt; top3(n);
    for (const auto&amp; e : edges) {      
      top3[e[0]].emplace(scores[e[1]], e[1]);
      top3[e[1]].emplace(scores[e[0]], e[0]);
      if (top3[e[0]].size() &gt; 3) top3[e[0]].erase(begin(top3[e[0]]));
      if (top3[e[1]].size() &gt; 3) top3[e[1]].erase(begin(top3[e[1]]));
    }
    int ans = -1;
    for (const auto&amp; e : edges) {
      const int a = e[0], b = e[1], sa = scores[a], sb = scores[b];
      for (const auto&amp; [sc, c] : top3[a])
        for (const auto&amp; [sd, d] : top3[b])          
          if (sa + sb + sc + sd &gt; ans &amp;&amp; c != b &amp;&amp; c != d &amp;&amp; d != a)
            ans = sa + sb + sc + sd;
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-2242-maximum-score-of-a-node-sequence/">花花酱 LeetCode 2242. Maximum Score of a Node Sequence</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-2242-maximum-score-of-a-node-sequence/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2102. Sequentially Ordinal Rank Tracker</title>
		<link>https://zxi.mytechroad.com/blog/data-structure/leetcode-2102-sequentially-ordinal-rank-tracker/</link>
					<comments>https://zxi.mytechroad.com/blog/data-structure/leetcode-2102-sequentially-ordinal-rank-tracker/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 12 Dec 2021 22:07:45 +0000</pubDate>
				<category><![CDATA[Data Structure]]></category>
		<category><![CDATA[data structure]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[iterator]]></category>
		<category><![CDATA[set]]></category>
		<category><![CDATA[treeset]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9143</guid>

					<description><![CDATA[<p>A scenic location is represented by its&#160;name&#160;and attractiveness&#160;score, where&#160;name&#160;is a&#160;unique&#160;string among all locations and&#160;score&#160;is an integer. Locations can be ranked from the best to the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/data-structure/leetcode-2102-sequentially-ordinal-rank-tracker/">花花酱 LeetCode 2102. Sequentially Ordinal Rank Tracker</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>A scenic location is represented by its&nbsp;<code>name</code>&nbsp;and attractiveness&nbsp;<code>score</code>, where&nbsp;<code>name</code>&nbsp;is a&nbsp;<strong>unique</strong>&nbsp;string among all locations and&nbsp;<code>score</code>&nbsp;is an integer. Locations can be ranked from the best to the worst. The&nbsp;<strong>higher</strong>&nbsp;the score, the better the location. If the scores of two locations are equal, then the location with the&nbsp;<strong>lexicographically smaller</strong>&nbsp;name is better.</p>



<p>You are building a system that tracks the ranking of locations with the system initially starting with no locations. It supports:</p>



<ul><li><strong>Adding</strong>&nbsp;scenic locations,&nbsp;<strong>one at a time</strong>.</li><li><strong>Querying</strong>&nbsp;the&nbsp;<code>i<sup>th</sup></code>&nbsp;<strong>best</strong>&nbsp;location of&nbsp;<strong>all locations already added</strong>, where&nbsp;<code>i</code>&nbsp;is the number of times the system has been queried (including the current query).<ul><li>For example, when the system is queried for the&nbsp;<code>4<sup>th</sup></code>&nbsp;time, it returns the&nbsp;<code>4<sup>th</sup></code>&nbsp;best location of all locations already added.</li></ul></li></ul>



<p>Note that the test data are generated so that&nbsp;<strong>at any time</strong>, the number of queries&nbsp;<strong>does not exceed</strong>&nbsp;the number of locations added to the system.</p>



<p>Implement the&nbsp;<code>SORTracker</code>&nbsp;class:</p>



<ul><li><code>SORTracker()</code>&nbsp;Initializes the tracker system.</li><li><code>void add(string name, int score)</code>&nbsp;Adds a scenic location with&nbsp;<code>name</code>&nbsp;and&nbsp;<code>score</code>&nbsp;to the system.</li><li><code>string get()</code>&nbsp;Queries and returns the&nbsp;<code>i<sup>th</sup></code>&nbsp;best location, where&nbsp;<code>i</code>&nbsp;is the number of times this method has been invoked (including this invocation).</li></ul>



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



<pre class="crayon-plain-tag">&lt;strong&gt;Input&lt;/strong&gt;
[&quot;SORTracker&quot;, &quot;add&quot;, &quot;add&quot;, &quot;get&quot;, &quot;add&quot;, &quot;get&quot;, &quot;add&quot;, &quot;get&quot;, &quot;add&quot;, &quot;get&quot;, &quot;add&quot;, &quot;get&quot;, &quot;get&quot;]
[[], [&quot;bradford&quot;, 2], [&quot;branford&quot;, 3], [], [&quot;alps&quot;, 2], [], [&quot;orland&quot;, 2], [], [&quot;orlando&quot;, 3], [], [&quot;alpine&quot;, 2], [], []]
&lt;strong&gt;Output&lt;/strong&gt;
[null, null, null, &quot;branford&quot;, null, &quot;alps&quot;, null, &quot;bradford&quot;, null, &quot;bradford&quot;, null, &quot;bradford&quot;, &quot;orland&quot;]
&lt;p&gt;&lt;strong&gt;Explanation&lt;/strong&gt; 
SORTracker tracker = new SORTracker(); // Initialize the tracker system.
tracker.add(&quot;bradford&quot;, 2);            // Add location with name=&quot;bradford&quot; and score=2 to the system.
tracker.add(&quot;branford&quot;, 3);            // Add location with name=&quot;branford&quot; and score=3 to the system.
tracker.get();                         // The sorted locations, from best to worst, are: branford, bradford. 
                                       // Note that branford precedes bradford due to its &lt;strong&gt;higher score&lt;/strong&gt; (3 &amp;gt; 2). 
                                       // This is the 1&lt;sup&gt;st&lt;/sup&gt; time get() is called, so return the best location: &quot;branford&quot;. 
tracker.add(&quot;alps&quot;, 2);                // Add location with name=&quot;alps&quot; and score=2 to the system.
tracker.get();                         // Sorted locations: branford, alps, bradford. 
                                       // Note that alps precedes bradford even though they have the same score (2). 
                                       // This is because &quot;alps&quot; is &lt;strong&gt;lexicographically smaller&lt;/strong&gt; than &quot;bradford&quot;. 
                                       // Return the 2&lt;sup&gt;nd&lt;/sup&gt; best location &quot;alps&quot;, as it is the 2&lt;sup&gt;nd&lt;/sup&gt; time get() is called.
tracker.add(&quot;orland&quot;, 2);              // Add location with name=&quot;orland&quot; and score=2 to the system.
tracker.get();                         // Sorted locations: branford, alps, bradford, orland. 
                                       // Return &quot;bradford&quot;, as it is the 3&lt;sup&gt;rd&lt;/sup&gt; time get() is called. 
tracker.add(&quot;orlando&quot;, 3);             // Add location with name=&quot;orlando&quot; and score=3 to the system.
tracker.get();                         // Sorted locations: branford, orlando, alps, bradford, orland. 
                                       // Return &quot;bradford&quot;. 
tracker.add(&quot;alpine&quot;, 2);              // Add location with name=&quot;alpine&quot; and score=2 to the system.
tracker.get();                         // Sorted locations: branford, orlando, alpine, alps, bradford, orland. 
                                       // Return &quot;bradford&quot;. 
tracker.get();                         // Sorted locations: branford, orlando, alpine, alps, bradford, orland. 
                                       // Return &quot;orland&quot;.
&lt;/p&gt;</pre>



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



<ul><li><code>name</code>&nbsp;consists of lowercase English letters, and is unique among all locations.</li><li><code>1 &lt;= name.length &lt;= 10</code></li><li><code>1 &lt;= score &lt;= 10<sup>5</sup></code></li><li>At any time, the number of calls to&nbsp;<code>get</code>&nbsp;does not exceed the number of calls to&nbsp;<code>add</code>.</li><li>At most&nbsp;<code>4 * 10<sup>4</sup></code>&nbsp;calls&nbsp;<strong>in total</strong>&nbsp;will be made to&nbsp;<code>add</code>&nbsp;and&nbsp;<code>get</code>.</li></ul>



<h2><strong>Solution: TreeSet w/ Iterator</strong></h2>



<p>Use a treeset to store all the entries and use a iterator that points to the entry to return. When inserting a new entry into the tree, if it&#8217;s higher than the current element then let the iterator go backward one step. </p>



<p>Time complexity:  add O(logn) / get O(1)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class SORTracker {
public:
  SORTracker() {}

  void add(string name, int score) {    
    if (*s.emplace(-score, name).first &lt; *cit) --cit;
  }

  string get() {
    return (cit++)-&gt;second;
  }
private:
  set&lt;pair&lt;int, string&gt;&gt; s;
  // Note: cit points to begin(s) after first insertion.
  set&lt;pair&lt;int, string&gt;&gt;::const_iterator cit = end(s);
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/data-structure/leetcode-2102-sequentially-ordinal-rank-tracker/">花花酱 LeetCode 2102. Sequentially Ordinal Rank Tracker</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-2102-sequentially-ordinal-rank-tracker/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1418. Display Table of Food Orders in a Restaurant</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-1418-display-table-of-food-orders-in-a-restaurant/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-1418-display-table-of-food-orders-in-a-restaurant/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 20 Apr 2020 07:32:06 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[map]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[set]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6646</guid>

					<description><![CDATA[<p>Given&#160;the array&#160;orders, which represents the orders that customers have done in a restaurant. More specifically&#160;orders[i]=[customerNamei,tableNumberi,foodItemi]&#160;where&#160;customerNamei&#160;is the name of the customer,&#160;tableNumberi&#160;is the table customer sit at,&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1418-display-table-of-food-orders-in-a-restaurant/">花花酱 LeetCode 1418. Display Table of Food Orders in a Restaurant</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&nbsp;the array&nbsp;<code>orders</code>, which represents the orders that customers have done in a restaurant. More specifically&nbsp;<code>orders[i]=[customerName<sub>i</sub>,tableNumber<sub>i</sub>,foodItem<sub>i</sub>]</code>&nbsp;where&nbsp;<code>customerName<sub>i</sub></code>&nbsp;is the name of the customer,&nbsp;<code>tableNumber<sub>i</sub></code>&nbsp;is the table customer sit at, and&nbsp;<code>foodItem<sub>i</sub></code>&nbsp;is the item customer orders.</p>



<p><em>Return the restaurant&#8217;s “<strong>display table</strong>”</em>. The “<strong>display table</strong>” is a table whose row entries denote how many of each food item each table ordered. The first column is the table number and the remaining columns correspond to each food item in alphabetical order. The first row should be a header whose first column is “Table”, followed by the names of the food items. Note that the customer names are not part of the table. Additionally, the rows should be sorted in numerically increasing order.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> orders = [["David","3","Ceviche"],["Corina","10","Beef Burrito"],["David","3","Fried Chicken"],["Carla","5","Water"],["Carla","5","Ceviche"],["Rous","3","Ceviche"]]
<strong>Output:</strong> [["Table","Beef Burrito","Ceviche","Fried Chicken","Water"],["3","0","2","1","0"],["5","0","1","0","1"],["10","1","0","0","0"]] 
<strong>Explanation:
</strong>The displaying table looks like:
<strong>Table,Beef Burrito,Ceviche,Fried Chicken,Water</strong>
3    ,0           ,2      ,1            ,0
5    ,0           ,1      ,0            ,1
10   ,1           ,0      ,0            ,0
For the table 3: David orders "Ceviche" and "Fried Chicken", and Rous orders "Ceviche".
For the table 5: Carla orders "Water" and "Ceviche".
For the table 10: Corina orders "Beef Burrito". 
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> orders = [["James","12","Fried Chicken"],["Ratesh","12","Fried Chicken"],["Amadeus","12","Fried Chicken"],["Adam","1","Canadian Waffles"],["Brianna","1","Canadian Waffles"]]
<strong>Output:</strong> [["Table","Canadian Waffles","Fried Chicken"],["1","2","0"],["12","0","3"]] 
<strong>Explanation:</strong> 
For the table 1: Adam and Brianna order "Canadian Waffles".
For the table 12: James, Ratesh and Amadeus order "Fried Chicken".
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> orders = [["Laura","2","Bean Burrito"],["Jhon","2","Beef Burrito"],["Melissa","2","Soda"]]
<strong>Output:</strong> [["Table","Bean Burrito","Beef Burrito","Soda"],["2","1","1","1"]]
</pre>



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



<ul><li><code>1 &lt;=&nbsp;orders.length &lt;= 5 * 10^4</code></li><li><code>orders[i].length == 3</code></li><li><code>1 &lt;= customerName<sub>i</sub>.length, foodItem<sub>i</sub>.length &lt;= 20</code></li><li><code>customerName<sub>i</sub></code>&nbsp;and&nbsp;<code>foodItem<sub>i</sub></code>&nbsp;consist of lowercase and uppercase English letters and the space character.</li><li><code>tableNumber<sub>i</sub>&nbsp;</code>is a valid integer between&nbsp;<code>1</code>&nbsp;and&nbsp;<code>500</code>.</li></ul>



<p>Solution: TreeMap/Set + HashTable</p>



<p>Time complexity: O(nlogn)<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:
  vector&lt;vector&lt;string&gt;&gt; displayTable(vector&lt;vector&lt;string&gt;&gt;&amp; orders) {
    map&lt;int, unordered_map&lt;string, int&gt;&gt; tables;
    set&lt;string&gt; foods;
    for (const auto&amp; order : orders) {
      ++tables[stoi(order[1])][order[2]];
      foods.insert(order[2]);
    }
    vector&lt;vector&lt;string&gt;&gt; ans;
    ans.push_back({{&quot;Table&quot;}});    
    ans.back().insert(end(ans.back()), begin(foods), end(foods));
    for (auto&amp; [table, m] : tables) {
      vector&lt;string&gt; line{to_string(table)};
      for (const auto&amp; food : foods)
        line.push_back(to_string(m[food]));
      ans.push_back(move(line));
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1418-display-table-of-food-orders-in-a-restaurant/">花花酱 LeetCode 1418. Display Table of Food Orders in a Restaurant</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-1418-display-table-of-food-orders-in-a-restaurant/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1353. Maximum Number of Events That Can Be Attended</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-1353-maximum-number-of-events-that-can-be-attended/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-1353-maximum-number-of-events-that-can-be-attended/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 17 Feb 2020 00:54:11 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[set]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6333</guid>

					<description><![CDATA[<p>Given an array of&#160;events&#160;where&#160;events[i] = [startDayi, endDayi]. Every event&#160;i&#160;starts at&#160;startDayiand ends at&#160;endDayi. You can attend an event&#160;i&#160;at any day&#160;d&#160;where&#160;startTimei&#160;&#60;= d &#60;= endTimei. Notice that you&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1353-maximum-number-of-events-that-can-be-attended/">花花酱 LeetCode 1353. Maximum Number of Events That Can Be Attended</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-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1353. Maximum Number of Events That Can Be Attended - 刷题找工作 EP308" width="500" height="281" src="https://www.youtube.com/embed/NjF9JGDGxg8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given an array of&nbsp;<code>events</code>&nbsp;where&nbsp;<code>events[i] = [startDay<sub>i</sub>, endDay<sub>i</sub>]</code>. Every event&nbsp;<code>i</code>&nbsp;starts at&nbsp;<code>startDay<sub>i</sub></code>and ends at&nbsp;<code>endDay<sub>i</sub></code>.</p>



<p>You can attend an event&nbsp;<code>i</code>&nbsp;at any day&nbsp;<code>d</code>&nbsp;where&nbsp;<code>startTime<sub>i</sub>&nbsp;&lt;= d &lt;= endTime<sub>i</sub></code>. Notice that you can only attend one event at any time&nbsp;<code>d</code>.</p>



<p>Return&nbsp;<em>the maximum number of events&nbsp;</em>you can attend.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/02/05/e1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> events = [[1,2],[2,3],[3,4]]
<strong>Output:</strong> 3
<strong>Explanation:</strong> You can attend all the three events.
One way to attend them all is as shown.
Attend the first event on day 1.
Attend the second event on day 2.
Attend the third event on day 3.
</pre>



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



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



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



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



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



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



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



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



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



<ul><li><code>1 &lt;= events.length &lt;= 10^5</code></li><li><code>events[i].length == 2</code></li><li><code>1 &lt;= events[i][0] &lt;= events[i][1] &lt;= 10^5</code></li></ul>



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



<p>Sort events by end time, for each event find the first available day to attend.</p>



<p>Time complexity: O(sum(endtime &#8211; starttime)) = O(10^10)<br>Space complexity: O(max(endtime &#8211; starttime) = O(10^5)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua, 216 ms, 45.7 MB
class Solution {
public:
  int maxEvents(vector&lt;vector&lt;int&gt;&gt;&amp; events) {
    sort(begin(events), end(events), [](const auto&amp; a, const auto&amp; b){      
      return a[1] &lt; b[1];      
    });
    int ans = 0;
    int seen[100001] = {0};
    for (const auto&amp; e : events) {
      for (int i = e[0]; i &lt;= e[1]; ++i) {
        if (seen[i]) continue;
        ++seen[i];
        ++ans;
        break;
      }
    }
    return ans;
  }
};</pre>
</div></div>



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

<pre class="crayon-plain-tag">// Author: Huahua, 216 ms, 45.6 MB
class Solution {
public:
  int maxEvents(vector&lt;vector&lt;int&gt;&gt;&amp; events) {
    sort(begin(events), end(events), [](const auto&amp; a, const auto&amp; b){      
      return a[1] &lt; b[1];      
    });
    int ans = 0;
    unsigned char seen[100000 / 8 + 1] = {0};
    for (const auto&amp; e : events) {
      for (int i = e[0]; i &lt;= e[1]; ++i) {
        if (seen[i &gt;&gt; 3] &amp; (1 &lt;&lt; (i % 8))) continue;
        seen[i &gt;&gt; 3] |= 1 &lt;&lt; (i % 8);
        ++ans;
        break;
      }
    }
    return ans;
  }
};</pre>
</div></div>



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

<pre class="crayon-plain-tag">// Author: Huahua, 824 ms
class Solution:
  def maxEvents(self, events: List[List[int]]) -&amp;gt; int:
    lo = min(e[0] for e in events)
    hi = max(e[1] for e in events)
    seen = [0] * (hi - lo + 1)
    for s, t in sorted(events, key=lambda e:e[1]):
      for i in range(s, t + 1):
        if seen[i - lo]: continue
        seen[i - lo] = 1
        break
    return sum(seen)</pre>
</div></div>



<p>We can use a TreeSet to maintain the open days and do a binary search to find the first available day. </p>



<p>Time complexity: O(nlogd)<br>Space complexity: O(d)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua, 416 ms, 46.1MB
class Solution {
public:
  int maxEvents(vector&lt;vector&lt;int&gt;&gt;&amp; events) {    
    sort(begin(events), end(events), [](const auto&amp; a, const auto&amp; b){      
      return a[1] &lt; b[1];
    });    
    int min_d = INT_MAX;
    int max_d = INT_MIN;
    for (const auto&amp; e : events) {
      min_d = min(min_d, e[0]);
      max_d = max(max_d, e[1]);
    }
    vector&lt;int&gt; days(max_d - min_d + 1);
    iota(begin(days), end(days), min_d);
    set&lt;int&gt; s(begin(days), end(days)); // O(n)
    
    int ans = 0;
    for (const auto&amp; e : events) {
      auto it = s.lower_bound(e[0]);
      if (it == end(s) || *it &gt; e[1]) continue;
      s.erase(it);
      ++ans;
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1353-maximum-number-of-events-that-can-be-attended/">花花酱 LeetCode 1353. Maximum Number of Events That Can Be Attended</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-1353-maximum-number-of-events-that-can-be-attended/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 987. Vertical Order Traversal of a Binary Tree</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-987-vertical-order-traversal-of-a-binary-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-987-vertical-order-traversal-of-a-binary-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 03 Feb 2019 07:19:39 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[map]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[set]]></category>
		<category><![CDATA[traversal]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4772</guid>

					<description><![CDATA[<p>Given a binary tree, return the&#160;vertical order&#160;traversal of its nodes&#160;values. For each node at position&#160;(X, Y), its left and right children respectively&#160;will be at positions&#160;(X-1,&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-987-vertical-order-traversal-of-a-binary-tree/">花花酱 LeetCode 987. Vertical Order Traversal of a Binary 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[
<p>Given a binary tree, return the&nbsp;<em>vertical order</em>&nbsp;traversal of its nodes&nbsp;values.</p>



<p>For each node at position&nbsp;<code>(X, Y)</code>, its left and right children respectively&nbsp;will be at positions&nbsp;<code>(X-1, Y-1)</code>&nbsp;and&nbsp;<code>(X+1, Y-1)</code>.</p>



<p>Running a vertical line from&nbsp;<code>X = -infinity</code>&nbsp;to&nbsp;<code>X = +infinity</code>, whenever the vertical line touches some nodes, we report the values of the nodes in order from top to bottom (decreasing&nbsp;<code>Y</code>&nbsp;coordinates).</p>



<p>If two nodes have the same position, then the value of the node that is reported first is the value that is smaller.</p>



<p>Return an list&nbsp;of non-empty reports in order of&nbsp;<code>X</code>&nbsp;coordinate.&nbsp; Every report will have a list of values of nodes.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/01/31/1236_example_1.PNG" alt=""/></figure>



<pre class="wp-block-preformatted crayon:false"><strong>Input: </strong>[3,9,20,null,null,15,7]
<strong>Output: </strong>[[9],[3,15],[20],[7]]
<strong>Explanation: </strong>
Without loss of generality, we can assume the root node is at position (0, 0):
Then, the node with value 9 occurs at position (-1, -1);
The nodes with values 3 and 15 occur at positions (0, 0) and (0, -2);
The node with value 20 occurs at position (1, -1);
The node with value 7 occurs at position (2, -2).
</pre>



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



<figure class="wp-block-image is-resized"><img src="https://assets.leetcode.com/uploads/2019/01/31/tree2.png" alt="" width="294" height="187"/></figure>



<pre class="wp-block-preformatted crayon:false"><strong>Input: </strong>[1,2,3,4,5,6,7]
<strong>Output: </strong>[[4],[2],[1,5,6],[3],[7]]
<strong>Explanation: </strong>
The node with value 5 and the node with value 6 have the same position according to the given scheme.
However, in the report "[1,5,6]", the node value of 5 comes first since 5 is smaller than 6.
</pre>



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



<ol><li>The tree will have between&nbsp;1&nbsp;and&nbsp;<code>1000</code>&nbsp;nodes.</li><li>Each node&#8217;s value will be between&nbsp;<code>0</code>&nbsp;and&nbsp;<code>1000</code>.</li></ol>



<h2><strong>Solution: Ordered Map+ Ordered Set</strong></h2>



<p>Time complexity: O(nlogn)<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, running time: 0 ms, 921.6 KB 
class Solution {
public:
  vector&lt;vector&lt;int&gt;&gt; verticalTraversal(TreeNode* root) {
    if (!root) return {};
    int min_x = INT_MAX;
    int max_x = INT_MIN;
    map&lt;pair&lt;int, int&gt;, multiset&lt;int&gt;&gt; h; // {y, x} -&gt; {vals}
    traverse(root, 0, 0, h, min_x, max_x);
    vector&lt;vector&lt;int&gt;&gt; ans(max_x - min_x + 1);
    for (const auto&amp; m : h) {      
      int x = m.first.second - min_x;
      ans[x].insert(end(ans[x]), begin(m.second), end(m.second));
    }
    return ans;
  }
private:
  void traverse(TreeNode* root, int x, int y, 
                map&lt;pair&lt;int, int&gt;, multiset&lt;int&gt;&gt;&amp; h,
                int&amp; min_x,
                int&amp; max_x) {
    if (!root) return;
    min_x = min(min_x, x);
    max_x = max(max_x, x);    
    h[{y, x}].insert(root-&gt;val);
    traverse(root-&gt;left, x - 1, y + 1, h, min_x, max_x);
    traverse(root-&gt;right, x + 1, y + 1, h, min_x, max_x);
  }
};</pre>

</div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag"># Author: Huahua, 36 ms, 6.8 MB
class Solution:
  def verticalTraversal(self, root: 'TreeNode') -&gt; 'List[List[int]]':
    if not root: return []    
    vals = []
    def preorder(root, x, y):
      if not root: return
      vals.append((x, y, root.val))
      preorder(root.left, x - 1, y + 1)
      preorder(root.right, x + 1, y + 1)
    preorder(root, 0, 0)    
    ans = []
    last_x = -1000
    for x, y, val in sorted(vals):
      if x != last_x:
        ans.append([])
        last_x = x
      ans[-1].append(val)
    return ans</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-987-vertical-order-traversal-of-a-binary-tree/">花花酱 LeetCode 987. Vertical Order Traversal of a Binary 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-987-vertical-order-traversal-of-a-binary-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 855. Exam Room</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-855-exam-room/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-855-exam-room/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 29 Jul 2018 21:28:53 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[BST]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[set]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3374</guid>

					<description><![CDATA[<p>Problem In an exam room, there are N seats in a single row, numbered 0, 1, 2, ..., N-1. When a student enters the room, they must sit&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-855-exam-room/">花花酱 LeetCode 855. Exam Room</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>In an exam room, there are <code>N</code> seats in a single row, numbered <code>0, 1, 2, ..., N-1</code>.</p>
<p>When a student enters the room, they must sit in the seat that maximizes the distance to the closest person.  If there are multiple such seats, they sit in the seat with the lowest number.  (Also, if no one is in the room, then the student sits at seat number 0.)</p>
<p>Return a class <code>ExamRoom(int N)</code> that exposes two functions: <code>ExamRoom.seat()</code> returning an <code>int</code> representing what seat the student sat in, and <code>ExamRoom.leave(int p)</code> representing that the student in seat number <code>p</code> now leaves the room.  It is guaranteed that any calls to <code>ExamRoom.leave(p)</code> have a student sitting in seat <code>p</code>.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-1-1">["ExamRoom","seat","seat","seat","seat","leave","seat"]</span>, <span id="example-input-1-2">[[10],[],[],[],[],[4],[]]</span>
<strong>Output: </strong><span id="example-output-1">[null,0,9,4,2,null,5]</span>
<strong>Explanation</strong>:
ExamRoom(10) -&gt; null
seat() -&gt; 0, no one is in the room, then the student sits at seat number 0.
seat() -&gt; 9, the student sits at the last seat number 9.
seat() -&gt; 4, the student sits at the last seat number 4.
seat() -&gt; 2, the student sits at the last seat number 2.
leave(4) -&gt; null
seat() -&gt; 5, the student​​​​​​​ sits at the last seat number 5.
</pre>
<p>​​​​<strong>Note:</strong></p>
<ol>
<li><code>1 &lt;= N &lt;= 10^9</code></li>
<li><code>ExamRoom.seat()</code> and <code>ExamRoom.leave()</code> will be called at most <code>10^4</code> times across all test cases.</li>
<li>Calls to <code>ExamRoom.leave(p)</code> are guaranteed to have a student currently sitting in seat number <code>p</code>.</li>
</ol>
<h1><strong>Solution: BST</strong></h1>
<p>Use a BST (ordered set) to track the current seatings.</p>
<p>Time Complexity:</p>
<p>init: O(1)</p>
<p>seat: O(P)</p>
<p>leave: O(logP)</p>
<p>Space complexity: O(P)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 24 ms
class ExamRoom {
public:
  ExamRoom(int N): N_(N) {}

  int seat() {
    int p = 0;
    int max_dist = s_.empty() ? 0 : *s_.begin();
    auto left = s_.begin();    
    auto right = left;
    while (left != s_.end()) {
      ++right;
      int l = *left;
      int r = right != s_.end() ? *right : (2 * (N_ - 1) - *left);      
      int d = (r - l) / 2;      
      if (d &gt; max_dist) {
        max_dist = d;
        p = l + d;
      }
      left = right;
    }    
    s_.insert(p);
    return p;
  }

  void leave(int p) {
    s_.erase(p);
  }

private:
  const int N_;
  set&lt;int&gt; s_;
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-855-exam-room/">花花酱 LeetCode 855. Exam Room</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-855-exam-room/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 414. Third Maximum Number</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-414-third-maximum-number/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-414-third-maximum-number/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 17 Mar 2018 20:07:54 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[max]]></category>
		<category><![CDATA[ordered]]></category>
		<category><![CDATA[set]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2170</guid>

					<description><![CDATA[<p>Problem https://leetcode.com/problems/third-maximum-number/description/ Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-414-third-maximum-number/">花花酱 LeetCode 414. Third Maximum 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[<h1><strong>Problem</strong></h1>
<p><a href="https://leetcode.com/problems/third-maximum-number/description/">https://leetcode.com/problems/third-maximum-number/description/</a></p>
<p>Given a <b>non-empty</b> array of integers, return the <b>third</b> maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).</p>
<p><b>Example 1:</b></p>
<pre class="crayon:false"><b>Input:</b> [3, 2, 1]

<b>Output:</b> 1

<b>Explanation:</b> The third maximum is 1.
</pre>
<p><b>Example 2:</b></p>
<pre class="crayon:false"><b>Input:</b> [1, 2]

<b>Output:</b> 2

<b>Explanation:</b> The third maximum does not exist, so the maximum (2) is returned instead.
</pre>
<p><b>Example 3:</b></p>
<pre class="crayon:false "><b>Input:</b> [2, 2, 3, 1]

<b>Output:</b> 1

<b>Explanation:</b> Note that the third maximum here means the third maximum distinct number.
Both numbers with value 2 are both considered as second maximum.</pre>
<h1><strong>Solution: Set</strong></h1>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(1)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 9 ms
class Solution {
public:
  int thirdMax(vector&lt;int&gt;&amp; nums) {
    set&lt;int&gt; s;
    for (int num : nums) {
      s.insert(num);
      if (s.size() &gt; 3) s.erase(s.begin());
    }
    return s.size() != 3 ? *s.rbegin() : *s.begin();
  }
};</pre><p>Python3</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 52 ms
"""
class Solution:
  def thirdMax(self, nums):
    s = set()
    for num in nums:
      s.add(num)
      if len(s) &gt; 3: s.remove(min(s))
    return min(s) if len(s) == 3 else max(s)</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-414-third-maximum-number/">花花酱 LeetCode 414. Third Maximum 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/algorithms/array/leetcode-414-third-maximum-number/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 349. Intersection of Two Arrays</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-349-intersection-of-two-arrays/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-349-intersection-of-two-arrays/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 08 Mar 2018 16:20:07 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[intersection]]></category>
		<category><![CDATA[set]]></category>
		<category><![CDATA[sorting]]></category>
		<category><![CDATA[unique]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2037</guid>

					<description><![CDATA[<p>题目大意：求2个数组的交集。 Problem: https://leetcode.com/problems/intersection-of-two-arrays/description/ Given two arrays, write a function to compute their intersection. Example: Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2]. Note: Each element in the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-349-intersection-of-two-arrays/">花花酱 LeetCode 349. Intersection of Two Arrays</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>题目大意：求2个数组的交集。</p>
<p><strong>Problem:</strong></p>
<p><a href="https://leetcode.com/problems/intersection-of-two-arrays/description/">https://leetcode.com/problems/intersection-of-two-arrays/description/</a></p>
<p>Given two arrays, write a function to compute their intersection.</p>
<p><b>Example:</b><br />
Given <i>nums1</i> = <code>[1, 2, 2, 1]</code>, <i>nums2</i> = <code>[2, 2]</code>, return <code>[2]</code>.</p>
<p><b>Note:</b></p>
<ul>
<li>Each element in the result must be unique.</li>
<li>The result can be in any order.</li>
</ul>
<p>C++ using std::set_intersection</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 8 ms
class Solution {
public:
  vector&lt;int&gt; intersection(vector&lt;int&gt;&amp; nums1, vector&lt;int&gt;&amp; nums2) {
    vector&lt;int&gt; intersection(max(nums1.size(), nums2.size()));
    std::sort(nums1.begin(), nums1.end());
    std::sort(nums2.begin(), nums2.end());
    // Inputs must be in ascending order
    auto it = std::set_intersection(nums1.begin(), nums1.end(), nums2.begin(), nums2.end(), intersection.begin());
    intersection.resize(it - intersection.begin());
    std::set&lt;int&gt; s(intersection.begin(), intersection.end());
    return vector&lt;int&gt;(s.begin(), s.end());
  }
};</pre><p>C++ hashtable</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 7 ms
class Solution {
public:
  vector&lt;int&gt; intersection(vector&lt;int&gt;&amp; nums1, vector&lt;int&gt;&amp; nums2) {
    unordered_set&lt;int&gt; m(nums1.begin(), nums1.end());
    vector&lt;int&gt; ans;
    for (int num : nums2) {
      if (!m.count(num)) continue;
      ans.push_back(num);
      m.erase(num);
    }
    return ans;
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-349-intersection-of-two-arrays/">花花酱 LeetCode 349. Intersection of Two Arrays</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-349-intersection-of-two-arrays/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
