<?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>queue Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/queue/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/queue/</link>
	<description></description>
	<lastBuildDate>Mon, 15 Nov 2021 16:58:32 +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>queue Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/queue/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2073. Time Needed to Buy Tickets</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-2073-time-needed-to-buy-tickets/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-2073-time-needed-to-buy-tickets/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 15 Nov 2021 16:57:40 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[queue]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8708</guid>

					<description><![CDATA[<p>There are&#160;n&#160;people in a line queuing to buy tickets, where the&#160;0th&#160;person is at the&#160;front&#160;of the line and the&#160;(n - 1)th&#160;person is at the&#160;back&#160;of the line.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-2073-time-needed-to-buy-tickets/">花花酱 LeetCode 2073. Time Needed to Buy Tickets</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 are&nbsp;<code>n</code>&nbsp;people in a line queuing to buy tickets, where the&nbsp;<code>0<sup>th</sup></code>&nbsp;person is at the&nbsp;<strong>front</strong>&nbsp;of the line and the&nbsp;<code>(n - 1)<sup>th</sup></code>&nbsp;person is at the&nbsp;<strong>back</strong>&nbsp;of the line.</p>



<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>tickets</code>&nbsp;of length&nbsp;<code>n</code>&nbsp;where the number of tickets that the&nbsp;<code>i<sup>th</sup></code>&nbsp;person would like to buy is&nbsp;<code>tickets[i]</code>.</p>



<p>Each person takes&nbsp;<strong>exactly 1 second</strong>&nbsp;to buy a ticket. A person can only buy&nbsp;<strong>1 ticket at a time</strong>&nbsp;and has to go back to&nbsp;<strong>the end</strong>&nbsp;of the line (which happens&nbsp;<strong>instantaneously</strong>) in order to buy more tickets. If a person does not have any tickets left to buy, the person will&nbsp;<strong>leave&nbsp;</strong>the line.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>time taken</strong>&nbsp;for the person at position&nbsp;</em><code>k</code><strong><em>(0-indexed)</em>&nbsp;</strong><em>to finish buying tickets</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> tickets = [2,3,2], k = 2
<strong>Output:</strong> 6
<strong>Explanation:</strong> 
- In the first pass, everyone in the line buys a ticket and the line becomes [1, 2, 1].
- In the second pass, everyone in the line buys a ticket and the line becomes [0, 1, 0].
The person at&nbsp;position 2 has successfully bought 2 tickets and it took 3 + 3 = 6 seconds.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> tickets = [5,1,1,1], k = 0
<strong>Output:</strong> 8
<strong>Explanation:</strong>
- In the first pass, everyone in the line buys a ticket and the line becomes [4, 0, 0, 0].
- In the next 4 passes, only the person in position 0 is buying tickets.
The person at&nbsp;position 0 has successfully bought 5 tickets and it took 4 + 1 + 1 + 1 + 1 = 8 seconds.
</pre>



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



<ul><li><code>n == tickets.length</code></li><li><code>1 &lt;= n &lt;= 100</code></li><li><code>1 &lt;= tickets[i] &lt;= 100</code></li><li><code>0 &lt;= k &lt; n</code></li></ul>



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



<p>Time complexity: O(n * tickets[k])<br>Space complexity: O(n) / O(1)</p>



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

<pre class="crayon-plain-tag">// Author: huahua
class Solution {
public:
  int timeRequiredToBuy(vector&lt;int&gt;&amp; tickets, int k) {
    const int n = tickets.size();
    queue&lt;pair&lt;int, int&gt;&gt; q;
    for (int i = 0; i &lt; n; ++i)
      q.emplace(i, tickets[i]);
    int ans = 0;
    while (!q.empty()) {
      ++ans;
      auto [i, t] = q.front(); q.pop();      
      if (--t == 0 &amp;&amp; k == i) return ans;
      if (t) q.emplace(i, t);
    }
    return -1;
  }
};</pre>
</div></div>



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



<p>Each person before k will have tickets[k] rounds, each person after k will have tickets[k] &#8211; 1 rounds.</p>



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



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

<pre class="crayon-plain-tag">// Author: huahua
class Solution {
public:
  int timeRequiredToBuy(vector&lt;int&gt;&amp; tickets, int k) {
    int ans = 0;
    for (int i = 0; i &lt; tickets.size(); ++i)
      ans += min(tickets[i], tickets[k] - (i &gt; k));
    return ans;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-2073-time-needed-to-buy-tickets/">花花酱 LeetCode 2073. Time Needed to Buy Tickets</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-2073-time-needed-to-buy-tickets/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1823. Find the Winner of the Circular Game</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-1823-find-the-winner-of-the-circular-game/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-1823-find-the-winner-of-the-circular-game/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 13 Apr 2021 06:28:01 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[queue]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8342</guid>

					<description><![CDATA[<p>There are&#160;n&#160;friends that are playing a game. The friends are sitting in a circle and are numbered from&#160;1&#160;to&#160;n&#160;in&#160;clockwise order. More formally, moving clockwise from the&#160;ith&#160;friend&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-1823-find-the-winner-of-the-circular-game/">花花酱 LeetCode 1823. Find the Winner of the Circular Game</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 are&nbsp;<code>n</code>&nbsp;friends that are playing a game. The friends are sitting in a circle and are numbered from&nbsp;<code>1</code>&nbsp;to&nbsp;<code>n</code>&nbsp;in&nbsp;<strong>clockwise order</strong>. More formally, moving clockwise from the&nbsp;<code>i<sup>th</sup></code>&nbsp;friend brings you to the&nbsp;<code>(i+1)<sup>th</sup></code>&nbsp;friend for&nbsp;<code>1 &lt;= i &lt; n</code>, and moving clockwise from the&nbsp;<code>n<sup>th</sup></code>&nbsp;friend brings you to the&nbsp;<code>1<sup>st</sup></code>&nbsp;friend.</p>



<p>The rules of the game are as follows:</p>



<ol><li><strong>Start</strong>&nbsp;at the&nbsp;<code>1<sup>st</sup></code>&nbsp;friend.</li><li>Count the next&nbsp;<code>k</code>&nbsp;friends in the clockwise direction&nbsp;<strong>including</strong>&nbsp;the friend you started at. The counting wraps around the circle and may count some friends more than once.</li><li>The last friend you counted leaves the circle and loses the game.</li><li>If there is still more than one friend in the circle, go back to step&nbsp;<code>2</code>&nbsp;<strong>starting</strong>&nbsp;from the friend&nbsp;<strong>immediately clockwise</strong>&nbsp;of the friend who just lost and repeat.</li><li>Else, the last friend in the circle wins the game.</li></ol>



<p>Given the number of friends,&nbsp;<code>n</code>, and an integer&nbsp;<code>k</code>, return&nbsp;<em>the winner of the game</em>.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/03/25/ic234-q2-ex11.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 5, k = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> Here are the steps of the game:
1) Start at friend 1.
2) Count 2 friends clockwise, which are friends 1 and 2.
3) Friend 2 leaves the circle. Next start is friend 3.
4) Count 2 friends clockwise, which are friends 3 and 4.
5) Friend 4 leaves the circle. Next start is friend 5.
6) Count 2 friends clockwise, which are friends 5 and 1.
7) Friend 1 leaves the circle. Next start is friend 3.
8) Count 2 friends clockwise, which are friends 3 and 5.
9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 6, k = 5
<strong>Output:</strong> 1
<strong>Explanation:</strong> The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1.
</pre>



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



<ul><li><code>1 &lt;= k &lt;= n &lt;= 500</code></li></ul>



<h2><strong>Solution 1: Simulation w/ Queue</strong> <strong>/ List</strong></h2>



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



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

<pre class="crayon-plain-tag">// Author: Huahua, 56 ms, 24.3 MB
class Solution {
public:
  int findTheWinner(int n, int k) {
    queue&lt;int&gt; q;
    for (int i = 1; i &lt;= n; ++i)
      q.push(i);
    
    while (q.size() != 1) {
      for (int i = 1; i &lt; k; ++i) {
        int x = q.front();
        q.pop();
        q.push(x);
      }
      q.pop();        
    }
    return q.front();
  }
};</pre>

</div><h2 class="tabtitle">C++/List</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua, 12 ms, 6.8 MB
class Solution {
public:
  int findTheWinner(int n, int k) {
    list&lt;int&gt; l;
    for (int i = 1; i &lt;= n; ++i)
      l.push_back(i);
    
    auto it = l.begin();
    while (l.size() != 1) {
      for (int i = 1; i &lt; k; ++i)
        if (++it == l.end()) 
          it = l.begin();
      it = l.erase(it);
      if (it == l.end()) 
        it = l.begin();
    }
    return l.front();
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-1823-find-the-winner-of-the-circular-game/">花花酱 LeetCode 1823. Find the Winner of the Circular Game</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-1823-find-the-winner-of-the-circular-game/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1701. Average Waiting Time</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-1701-average-waiting-time/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-1701-average-waiting-time/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 27 Dec 2020 01:11:00 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[queue]]></category>
		<category><![CDATA[time]]></category>
		<category><![CDATA[waiting]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7843</guid>

					<description><![CDATA[<p>There is a restaurant with a single chef. You are given an array&#160;customers, where&#160;customers[i] = [arrivali, timei]: arrivali&#160;is the arrival time of the&#160;ith&#160;customer. The arrival&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-1701-average-waiting-time/">花花酱 LeetCode 1701. Average Waiting Time</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 a restaurant with a single chef. You are given an array&nbsp;<code>customers</code>, where&nbsp;<code>customers[i] = [arrival<sub>i</sub>, time<sub>i</sub>]:</code></p>



<ul><li><code>arrival<sub>i</sub></code>&nbsp;is the arrival time of the&nbsp;<code>i<sup>th</sup></code>&nbsp;customer. The arrival times are sorted in&nbsp;<strong>non-decreasing</strong>&nbsp;order.</li><li><code>time<sub>i</sub></code>&nbsp;is the time needed to prepare the order of the&nbsp;<code>i<sup>th</sup></code>&nbsp;customer.</li></ul>



<p>When a customer arrives, he gives the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers&nbsp;<strong>in the order they were given in the input</strong>.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>average</strong>&nbsp;waiting time of all customers</em>. Solutions within&nbsp;<code>10<sup>-5</sup></code>&nbsp;from the actual answer are considered accepted.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> customers = [[1,2],[2,5],[4,3]]
<strong>Output:</strong> 5.00000
<strong>Explanation:
</strong>1) The first customer arrives at time 1, the chef takes his order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2.
2) The second customer arrives at time 2, the chef takes his order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6.
3) The third customer arrives at time 4, the chef takes his order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7.
So the average waiting time = (2 + 6 + 7) / 3 = 5.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> customers = [[5,2],[5,4],[10,3],[20,1]]
<strong>Output:</strong> 3.25000
<strong>Explanation:
</strong>1) The first customer arrives at time 5, the chef takes his order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2.
2) The second customer arrives at time 5, the chef takes his order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6.
3) The third customer arrives at time 10, the chef takes his order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4.
4) The fourth customer arrives at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1.
So the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25.
</pre>



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



<ul><li><code>1 &lt;= customers.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= arrival<sub>i</sub>, time<sub>i</sub>&nbsp;&lt;= 10<sup>4</sup></code></li><li><code>arrival<sub>i&nbsp;</sub>&lt;= arrival<sub>i+1</sub></code></li></ul>



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



<p>When a customer arrives, if the arrival time is greater than current, then advance the clock to arrival time. Advance the clock by cooking time. Waiting time  = current time &#8211; arrival time.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  double averageWaitingTime(vector&lt;vector&lt;int&gt;&gt;&amp; customers) {
    int t = 0;
    double w = 0;
    for (const auto&amp; c : customers) {
      if (c[0] &gt; t) t = c[0];
      t += c[1];
      w += t - c[0];
    }
    return w / customers.size();
  }
};</pre>

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

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def averageWaitingTime(self, customers: List[List[int]]) -&gt; float:
    cur = 0
    waiting = 0
    for arrival, time in customers:
      cur = max(cur, arrival) + time
      waiting += cur - arrival
    return waiting / len(customers)</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-1701-average-waiting-time/">花花酱 LeetCode 1701. Average Waiting Time</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-1701-average-waiting-time/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1700. Number of Students Unable to Eat Lunch</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-1700-number-of-students-unable-to-eat-lunch/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-1700-number-of-students-unable-to-eat-lunch/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 27 Dec 2020 00:28:07 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[queue]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7840</guid>

					<description><![CDATA[<p>The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers&#160;0&#160;and&#160;1&#160;respectively. All students stand in a queue. Each student either prefers&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-1700-number-of-students-unable-to-eat-lunch/">花花酱 LeetCode 1700. Number of Students Unable to Eat Lunch</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>The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers&nbsp;<code>0</code>&nbsp;and&nbsp;<code>1</code>&nbsp;respectively. All students stand in a queue. Each student either prefers square or circular sandwiches.</p>



<p>The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a&nbsp;<strong>stack</strong>. At each step:</p>



<ul><li>If the student at the front of the queue&nbsp;<strong>prefers</strong>&nbsp;the sandwich on the top of the stack, they will&nbsp;<strong>take it</strong>&nbsp;and leave the queue.</li><li>Otherwise, they will&nbsp;<strong>leave it</strong>&nbsp;and go to the queue&#8217;s end.</li></ul>



<p>This continues until none of the queue students want to take the top sandwich and are thus unable to eat.</p>



<p>You are given two integer arrays&nbsp;<code>students</code>&nbsp;and&nbsp;<code>sandwiches</code>&nbsp;where&nbsp;<code>sandwiches[i]</code>&nbsp;is the type of the&nbsp;<code>i<sup>​​​​​​th</sup></code>&nbsp;sandwich in the stack (<code>i = 0</code>&nbsp;is the top of the stack) and&nbsp;<code>students[j]</code>&nbsp;is the preference of the&nbsp;<code>j<sup>​​​​​​th</sup></code>&nbsp;student in the initial queue (<code>j = 0</code>&nbsp;is the front of the queue). Return&nbsp;<em>the number of students that are unable to eat.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> students = [1,1,0,0], sandwiches = [0,1,0,1]
<strong>Output:</strong> 0<strong> 
Explanation:</strong>
- Front student leaves the top sandwich and returns to the end of the line making students = [1,0,0,1].
- Front student leaves the top sandwich and returns to the end of the line making students = [0,0,1,1].
- Front student takes the top sandwich and leaves the line making students = [0,1,1] and sandwiches = [1,0,1].
- Front student leaves the top sandwich and returns to the end of the line making students = [1,1,0].
- Front student takes the top sandwich and leaves the line making students = [1,0] and sandwiches = [0,1].
- Front student leaves the top sandwich and returns to the end of the line making students = [0,1].
- Front student takes the top sandwich and leaves the line making students = [1] and sandwiches = [1].
- Front student takes the top sandwich and leaves the line making students = [] and sandwiches = [].
Hence all students are able to eat.
</pre>



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



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



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



<ul><li><code>1 &lt;= students.length, sandwiches.length &lt;= 100</code></li><li><code>students.length == sandwiches.length</code></li><li><code>sandwiches[i]</code>&nbsp;is&nbsp;<code>0</code>&nbsp;or&nbsp;<code>1</code>.</li><li><code>students[i]</code>&nbsp;is&nbsp;<code>0</code>&nbsp;or&nbsp;<code>1</code>.</li></ul>



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



<p>Time complexity: O(n^2)<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:
  int countStudents(vector&lt;int&gt;&amp; students, vector&lt;int&gt;&amp; sandwiches) {
    queue&lt;int&gt; q;
    for (int s : students) q.push(s);
    int c = 0;
    int i = 0;
    while (!q.empty()) {
      int s = q.front(); q.pop();      
      if (s == sandwiches[i]) {
        ++i;
        c = 0;
      } else {
        q.push(s);
      }
      if (++c &gt; q.size()) break;
    }
    return q.size();
  }
};</pre>
</div></div>



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



<p>Count student&#8217;s preferences. Then process students from 1 to n, if there is no sandwich for current student then we can stop, since he/she will block all the students behind him/her.  </p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int countStudents(vector&lt;int&gt;&amp; students, vector&lt;int&gt;&amp; sandwiches) {
    const int n = students.size();
    vector&lt;int&gt; c(2);
    for (int p : students) ++c[p];
    for (int i = 0; i &lt; n; ++i)
      if (--c[sandwiches[i]] &lt; 0) return n - i;
    return 0;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-1700-number-of-students-unable-to-eat-lunch/">花花酱 LeetCode 1700. Number of Students Unable to Eat Lunch</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-1700-number-of-students-unable-to-eat-lunch/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1417. Reformat The String</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-1417-reformat-the-string/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-1417-reformat-the-string/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 20 Apr 2020 07:13:16 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[interleaving]]></category>
		<category><![CDATA[queue]]></category>
		<category><![CDATA[stack]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6643</guid>

					<description><![CDATA[<p>Given alphanumeric string&#160;s. (Alphanumeric string&#160;is a string consisting of lowercase English letters and digits). You have to find a permutation of&#160;the string where no letter&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1417-reformat-the-string/">花花酱 LeetCode 1417. Reformat The String</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 alphanumeric string&nbsp;<code>s</code>. (<strong>Alphanumeric string</strong>&nbsp;is a string consisting of lowercase English letters and digits).</p>



<p>You have to find a permutation of&nbsp;the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type.</p>



<p>Return&nbsp;<em>the reformatted string</em>&nbsp;or return&nbsp;<strong>an empty string</strong>&nbsp;if it is impossible to reformat the string.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "a0b1c2"
<strong>Output:</strong> "0a1b2c"
<strong>Explanation:</strong> No two adjacent characters have the same type in "0a1b2c". "a0b1c2", "0a1b2c", "0c2a1b" are also valid permutations.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "leetcode"
<strong>Output:</strong> ""
<strong>Explanation:</strong> "leetcode" has only characters so we cannot separate them by digits.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "1229857369"
<strong>Output:</strong> ""
<strong>Explanation:</strong> "1229857369" has only digits so we cannot separate them by characters.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "covid2019"
<strong>Output:</strong> "c2o0v1i9d"
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "ab123"
<strong>Output:</strong> "1a2b3"
</pre>



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



<ul><li><code>1 &lt;= s.length &lt;= 500</code></li><li><code>s</code>&nbsp;consists of only lowercase English letters and/or digits.</li></ul>



<h2><strong>Solution: Two streams</strong></h2>



<p>Create two stacks, one for alphas, another for numbers. If the larger stack has more than one element than the other one then no solution, return &#8220;&#8221;. Otherwise, interleave two stacks, start with the larger one.</p>



<p>Time complexity: O(n)<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:
  string reformat(string s) {
    string q1;
    string q2;
    for (char c : s) {
      if (isalpha(c))
        q1 += c;
      else
        q2 += c;
    }    
    if (q1.length() &lt; q2.length())
      swap(q1, q2);
    if (q1.length() &gt; q2.length() + 1) 
      return &quot;&quot;;
    string ans;
    while (!q1.empty()) {
      ans += q1.back();
      q1.pop_back();
      if (q2.empty()) break;
      ans += q2.back();
      q2.pop_back();
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1417-reformat-the-string/">花花酱 LeetCode 1417. Reformat The String</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/string/leetcode-1417-reformat-the-string/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 133. Clone Graph</title>
		<link>https://zxi.mytechroad.com/blog/graph/leetcode-133-clone-graph/</link>
					<comments>https://zxi.mytechroad.com/blog/graph/leetcode-133-clone-graph/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 13 Feb 2019 16:34:14 +0000</pubDate>
				<category><![CDATA[Graph]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[queue]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4844</guid>

					<description><![CDATA[<p>Given the head of a&#160;graph, return a deep copy (clone) of the graph. Each node in the graph contains a&#160;label&#160;(int) and a list (List[UndirectedGraphNode]) of&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-133-clone-graph/">花花酱 LeetCode 133. Clone Graph</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 the head of a&nbsp;graph, return a deep copy (clone) of the graph. Each node in the graph contains a&nbsp;<code>label</code>&nbsp;(<code>int</code>) and a list (<code>List[UndirectedGraphNode]</code>) of its&nbsp;<code>neighbors</code>. There is an edge between the given node and each of the nodes in its neighbors.<br><strong>OJ&#8217;s undirected graph serialization (so you can understand error output):</strong></p>



<p>Nodes are labeled uniquely.We use&nbsp;<code>#</code>&nbsp;as a separator for each node, and&nbsp;<code>,</code>&nbsp;as a separator for node label and each neighbor of the node.</p>



<p>As an example, consider the serialized graph&nbsp;<code>{0,1,2#1,2#2,2}</code>.</p>



<p>The graph has a total of three nodes, and therefore contains three parts as separated by&nbsp;<code>#</code>.</p>



<ol><li>First node is labeled as&nbsp;<code>0</code>. Connect node&nbsp;<code>0</code>&nbsp;to both nodes&nbsp;<code>1</code>&nbsp;and&nbsp;<code>2</code>.</li><li>Second node is labeled as&nbsp;<code>1</code>. Connect node&nbsp;<code>1</code>&nbsp;to node&nbsp;<code>2</code>.</li><li>Third node is labeled as&nbsp;<code>2</code>. Connect node&nbsp;<code>2</code>&nbsp;to node&nbsp;<code>2</code>&nbsp;(itself), thus forming a self-cycle.</li></ol>



<p>Visually, the graph looks like the following:</p>



<pre class="wp-block-preformatted crayon:false">       1
      / \
     /   \
    0 --- 2
         / \
         \_/
</pre>



<p><strong>Note</strong>: The information about the tree serialization is only meant so that you can understand error output if you get a wrong answer. You don&#8217;t need to understand the serialization to solve the problem.</p>



<h2><strong>Solution: Queue + Hashtable</strong></h2>



<p>Time complexity: O(V+E)<br>Space complexity: O(V+E)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua, 44ms, 16.8MB
class Solution {
public:
  UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
    if (!node) return nullptr;
    typedef UndirectedGraphNode Node;
    unordered_set&lt;Node*&gt; done;
    unordered_map&lt;Node*, Node*&gt; m;    
    queue&lt;Node*&gt; q;
    q.push(node);
    while (!q.empty()) {
      Node* s = q.front(); q.pop();
      if (done.count(s)) continue;
      done.insert(s);
      if (!m.count(s))
        m[s] = new Node(s-&gt;label);
      Node* t = m[s];
      for (Node* ss : s-&gt;neighbors) {
        if (!m.count(ss))
          m[ss] = new Node(ss-&gt;label);
        q.push(ss);        
        t-&gt;neighbors.push_back(m[ss]);
      }
    }    
    return m[node];
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-133-clone-graph/">花花酱 LeetCode 133. Clone Graph</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/graph/leetcode-133-clone-graph/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 933. Number of Recent Calls</title>
		<link>https://zxi.mytechroad.com/blog/queue/leetcode-933-number-of-recent-calls/</link>
					<comments>https://zxi.mytechroad.com/blog/queue/leetcode-933-number-of-recent-calls/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 04 Nov 2018 08:20:59 +0000</pubDate>
				<category><![CDATA[Queue]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[queue]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4248</guid>

					<description><![CDATA[<p>Problem Write a class RecentCounter to count recent requests. It has only one method: ping(int t), where t represents some time in milliseconds. Return the number of pings that&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/queue/leetcode-933-number-of-recent-calls/">花花酱 LeetCode 933. Number of Recent Calls</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>Write a class <code>RecentCounter</code> to count recent requests.</p>
<p>It has only one method: <code>ping(int t)</code>, where t represents some time in milliseconds.</p>
<p>Return the number of <code>ping</code>s that have been made from 3000 milliseconds ago until now.</p>
<p>Any ping with time in <code>[t - 3000, t]</code> will count, including the current ping.</p>
<p>It is guaranteed that every call to <code>ping</code> uses a strictly larger value of <code>t</code> than before.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: </strong>inputs = <span id="example-input-1-1">["RecentCounter","ping","ping","ping","ping"]</span>, inputs = <span id="example-input-1-2">[[],[1],[100],[3001],[3002]]</span>
<strong>Output: </strong><span id="example-output-1">[null,1,2,3,3]</span></pre>
<p><strong>Note:</strong></p>
<ol>
<li>Each test case will have at most <code>10000</code> calls to <code>ping</code>.</li>
<li>Each test case will call <code>ping</code> with strictly increasing values of <code>t</code>.</li>
<li>Each call to ping will have <code>1 &lt;= t &lt;= 10^9</code>.</li>
</ol>
<h1>Solution: Queue</h1>
<p>Use a FIFO queue to track all the previous pings that are within 3000 ms to current.</p>
<p>Time complexity: Avg O(1), Total O(n)</p>
<p>Space complexity: O(n)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">class RecentCounter {
public:
    RecentCounter() {}
    
    int ping(int t) {
      while (!q.empty() &amp;&amp; t - q.front() &gt; 3000) q.pop();
      q.push(t);
      return q.size();
    }
private:
  queue&lt;int&gt; q;
};</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/queue/leetcode-933-number-of-recent-calls/">花花酱 LeetCode 933. Number of Recent Calls</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/queue/leetcode-933-number-of-recent-calls/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 622. Design Circular Queue</title>
		<link>https://zxi.mytechroad.com/blog/desgin/leetcode-622-design-circular-queue/</link>
					<comments>https://zxi.mytechroad.com/blog/desgin/leetcode-622-design-circular-queue/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 13 Jul 2018 05:37:46 +0000</pubDate>
				<category><![CDATA[Desgin]]></category>
		<category><![CDATA[data structure]]></category>
		<category><![CDATA[deque]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[queue]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3104</guid>

					<description><![CDATA[<p>Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/desgin/leetcode-622-design-circular-queue/">花花酱 LeetCode 622. Design Circular Queue</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>Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called &#8220;Ring Buffer&#8221;.</p>



<p>One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.</p>



<p>Your implementation should support following operations:</p>



<ul><li><code>MyCircularQueue(k)</code>: Constructor, set the size of the queue to be k.</li><li><code>Front</code>: Get the front item from the queue. If the queue is empty, return -1.</li><li><code>Rear</code>: Get the last item from the queue. If the queue is empty, return -1.</li><li><code>enQueue(value)</code>: Insert an element into the circular queue. Return true if the operation is successful.</li><li><code>deQueue()</code>: Delete an element from the circular queue. Return true if the operation is successful.</li><li><code>isEmpty()</code>: Checks whether the circular queue is empty or not.</li><li><code>isFull()</code>: Checks whether the circular queue is full or not.</li></ul>



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



<pre class="wp-block-preformatted;crayon:false">MyCircularQueue circularQueue = new MyCircularQueue(3); // set the size to be 3
circularQueue.enQueue(1); &nbsp;// return true
circularQueue.enQueue(2); &nbsp;// return true
circularQueue.enQueue(3); &nbsp;// return true
circularQueue.enQueue(4); &nbsp;// return false, the queue is full
circularQueue.Rear(); &nbsp;// return 3
circularQueue.isFull(); &nbsp;// return true
circularQueue.deQueue(); &nbsp;// return true
circularQueue.enQueue(4); &nbsp;// return true
circularQueue.Rear(); &nbsp;// return 4
</pre>



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



<ul><li>All values will be in the range of [0, 1000].</li><li>The number of operations will be in the range of&nbsp;[1, 1000].</li><li>Please do not use the built-in Queue library.</li></ul>



<h2><strong>Solution: Simulate with an array</strong></h2>



<p>We need a fixed length array, and the head location as well as the size of the current queue.</p>



<p>We can use q[head] to access the front, and q[(head + size &#8211; 1) % k] to access the rear.</p>



<p>Time complexity: O(1) for all the operations.<br>Space complexity: O(k)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class MyCircularQueue {
public:
  MyCircularQueue(int k): q_(k) {}
  
  bool enQueue(int value) {
    if (isFull()) return false;
    q_[(head_ + size_) % q_.size()] = value;    
    ++size_;
    return true;
  }
  
  bool deQueue() {
    if (isEmpty()) return false;
    head_ = (head_ + 1) % q_.size();
    --size_;
    return true;
  }

  int Front() { return isEmpty() ? -1 : q_[head_]; }

  int Rear() { return isEmpty() ? -1 : q_[(head_ + size_ - 1) % q_.size()]; }

  bool isEmpty() { return size_ == 0; }

  bool isFull() { return size_ == q_.size(); }
private:
  vector&lt;int&gt; q_;
  int head_ = 0;
  int size_ = 0;
};</pre>

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

<pre class="crayon-plain-tag">class MyCircularQueue {
  private int[] q;
  private int head;
  private int size;
  
  public MyCircularQueue(int k) {
    this.q = new int[k];
    this.head = 0;
    this.size = 0;
  }
  
  public boolean enQueue(int value) {
    if (this.isFull()) return false;    
    this.q[(this.head + this.size) % this.q.length] = value;
    ++this.size;
    return true;
  }

  public boolean deQueue() {
    if (this.isEmpty()) return false;
    this.head = (this.head + 1) % this.q.length;
    --this.size;
    return true;
  }

  public int Front() {
    return this.isEmpty() ? -1 : this.q[this.head];
  }

  public int Rear() {
    return this.isEmpty() ? -1 : this.q[(this.head + this.size - 1) % this.q.length];
  }

  public boolean isEmpty() { return this.size == 0; }  

  public boolean isFull() { return this.size == this.q.length; }
}</pre>

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

<pre class="crayon-plain-tag">class MyCircularQueue:
  def __init__(self, k: int):
    self.q = [0] * k
    self.k = k
    self.head = self.size = 0


  def enQueue(self, value: int) -&gt; bool:
    if self.isFull(): return False
    self.q[(self.head + self.size) % self.k] = value
    self.size += 1
    return True


  def deQueue(self) -&gt; bool:
    if self.isEmpty(): return False
    self.head = (self.head + 1) % self.k
    self.size -= 1
    return True


  def Front(self) -&gt; int:
    return -1 if self.isEmpty() else self.q[self.head]


  def Rear(self) -&gt; int:
    return -1 if self.isEmpty() else self.q[(self.head + self.size - 1) % self.k]


  def isEmpty(self) -&gt; bool:
    return self.size == 0


  def isFull(self) -&gt; bool:
    return self.size == self.k</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/desgin/leetcode-622-design-circular-queue/">花花酱 LeetCode 622. Design Circular Queue</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-622-design-circular-queue/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 225. Implement Stack using Queues</title>
		<link>https://zxi.mytechroad.com/blog/data-structure/leetcode-225-implement-stack-using-queues/</link>
					<comments>https://zxi.mytechroad.com/blog/data-structure/leetcode-225-implement-stack-using-queues/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 13 Mar 2018 09:59:56 +0000</pubDate>
				<category><![CDATA[Data Structure]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[queue]]></category>
		<category><![CDATA[stack]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2084</guid>

					<description><![CDATA[<p>题目大意：用队列来实现栈。 Problem: https://leetcode.com/problems/implement-stack-using-queues/description/ Implement the following operations of a stack using queues. push(x) &#8212; Push element x onto stack. pop() &#8212; Removes the element on&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/data-structure/leetcode-225-implement-stack-using-queues/">花花酱 LeetCode 225. Implement Stack using Queues</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>
<p><strong>Problem:</strong></p>
<p><a href="https://leetcode.com/problems/implement-stack-using-queues/description/">https://leetcode.com/problems/implement-stack-using-queues/description/</a></p>
<p>Implement the following operations of a stack using queues.</p>
<ul>
<li>push(x) &#8212; Push element x onto stack.</li>
<li>pop() &#8212; Removes the element on top of the stack.</li>
<li>top() &#8212; Get the top element.</li>
<li>empty() &#8212; Return whether the stack is empty.</li>
</ul>
<p><b>Notes:</b></p>
<ul>
<li>You must use <i>only</i> standard operations of a queue &#8212; which means only <code>push to back</code>, <code>peek/pop from front</code>, <code>size</code>, and <code>is empty</code> operations are valid.</li>
<li>Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.</li>
<li>You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).</li>
</ul>
<p><strong>Idea:</strong></p>
<p>Using a single queue, for every push, shift the queue (n &#8211; 1) times such that the last element becomes the first element in the queue.</p>
<p>e.g.</p>
<p>push(1): q: [1]</p>
<p>push(2): q: [1, 2] -&gt; [2, 1]</p>
<p>push(3): q: [2, 1, 3] -&gt; [1, 3, 2] -&gt; [3, 2, 1]</p>
<p>push(4): q: [3, 2, 1, 4] -&gt; [2, 1, 4, 3] -&gt; [1, 4, 3, 2] -&gt; [4, 3, 2, 1]</p>
<p><strong>Solution:</strong></p>
<p>Time complexity:</p>
<p>Push: O(n)</p>
<p>Pop/top/empty: O(1)</p>
<p>Space complexity: O(n)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 3 ms
class MyStack {
public:
  /** Initialize your data structure here. */
  MyStack() {}

  /** Push element x onto stack. */
  void push(int x) {
    q_.push(x);
    for (int i = 1; i &lt; q_.size(); ++i) {
      q_.push(q_.front());
      q_.pop();
    }
  }

  /** Removes the element on top of the stack and returns that element. */
  int pop() {
    int top = q_.front();
    q_.pop();
    return top;
  }

  /** Get the top element. */
  int top() {
    return q_.front();
  }

  /** Returns whether the stack is empty. */
  bool empty() {
    return q_.empty();
  }
private:
  queue&lt;int&gt; q_;  
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/data-structure/leetcode-225-implement-stack-using-queues/">花花酱 LeetCode 225. Implement Stack using Queues</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-225-implement-stack-using-queues/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 239. Sliding Window Maximum</title>
		<link>https://zxi.mytechroad.com/blog/heap/leetcode-239-sliding-window-maximum/</link>
					<comments>https://zxi.mytechroad.com/blog/heap/leetcode-239-sliding-window-maximum/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 25 Jan 2018 05:17:37 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[Data Structure]]></category>
		<category><![CDATA[Heap]]></category>
		<category><![CDATA[deque]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[queue]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1650</guid>

					<description><![CDATA[<p>题目大意：给你一个数组，让你输出移动窗口的最大值。 Problem: https://leetcode.com/problems/sliding-window-maximum/ Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/heap/leetcode-239-sliding-window-maximum/">花花酱 LeetCode 239. Sliding Window Maximum</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/2SXqBsTR6a8?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p>题目大意：给你一个数组，让你输出移动窗口的最大值。</p>
<p><strong>Problem:</strong></p>
<p><a href="https://leetcode.com/problems/sliding-window-maximum/">https://leetcode.com/problems/sliding-window-maximum/</a></p>
<p>Given an array <i>nums</i>, there is a sliding window of size <i>k</i> which is moving from the very left of the array to the very right. You can only see the <i>k</i> numbers in the window. Each time the sliding window moves right by one position.</p>
<p>For example,<br />
Given <i>nums</i> = <code>[1,3,-1,-3,5,3,6,7]</code>, and <i>k</i> = 3.</p><pre class="crayon-plain-tag">Window position                Max
---------------               -----
[1  3  -1] -3  5  3  6  7       3
 1 [3  -1  -3] 5  3  6  7       3
 1  3 [-1  -3  5] 3  6  7       5
 1  3  -1 [-3  5  3] 6  7       5
 1  3  -1  -3 [5  3  6] 7       6
 1  3  -1  -3  5 [3  6  7]      7</pre><p>Therefore, return the max sliding window as <code>[3,3,5,5,6,7]</code>.</p>
<p><b>Note: </b><br />
You may assume <i>k</i> is always valid, ie: 1 ≤ k ≤ input array&#8217;s size for non-empty array.</p>
<p><b>Follow up:</b><br />
Could you solve it in linear time?</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>
<p><strong>Idea:</strong></p>
<p><img class="alignnone size-full wp-image-1657" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/239-ep159.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/239-ep159.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/239-ep159-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/239-ep159-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p><img class="alignnone size-full wp-image-1656" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/239-ep159-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/239-ep159-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/239-ep159-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/239-ep159-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p>&nbsp;</p>
<h1><strong>Solution 1: Brute Force</strong></h1>
<p>Time complexity: O((n &#8211; k + 1) * k)</p>
<p>Space complexity: O(1)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 180 ms
class Solution {
public:
  vector&lt;int&gt; maxSlidingWindow(vector&lt;int&gt;&amp; nums, int k) {    
    vector&lt;int&gt; ans;
    for (int i = k - 1; i &lt; nums.size(); ++i) {
      ans.push_back(*max_element(nums.begin() + i - k + 1, nums.begin() + i + 1));
    }
    return ans;
  }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 80 ms
class Solution {
  public int[] maxSlidingWindow(int[] nums, int k) {
    if (k == 0) return new int[0];
    
    int[] ans = new int[nums.length - k + 1];    
    for (int i = k - 1; i &lt; nums.length; ++i) {
      int maxNum = nums[i];
      for (int j = 1; j &lt; k; ++j)
        if (nums[i - j] &gt; maxNum) maxNum = nums[i - j];
      ans[i - k + 1] = maxNum;
    }
    return ans;
  }
}</pre><p></div><h2 class="tabtitle">Python</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 1044 ms
"""
class Solution:
  def maxSlidingWindow(self, nums, k):
    if not nums: return []    
    return [max(nums[i:i+k]) for i in range(len(nums) - k + 1)]</pre><p></div></div></p>
<h1><strong>Solution 2: BST</strong></h1>
<p>Time complexity: O((n &#8211; k + 1) * logk)</p>
<p>Space complexity: O(k)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 82 ms
class Solution {
public:
  vector&lt;int&gt; maxSlidingWindow(vector&lt;int&gt;&amp; nums, int k) {
    vector&lt;int&gt; ans;
    if (nums.empty()) return ans;
    multiset&lt;int&gt; window(nums.begin(), nums.begin() + k - 1);
    for (int i = k - 1; i &lt; nums.size(); ++i) {
      window.insert(nums[i]);
      ans.push_back(*window.rbegin());
      if (i - k + 1 &gt;= 0)
        window.erase(window.equal_range(nums[i - k + 1]).first);      
    }
    return ans;
  }
};</pre><p></div></div></p>
<h1><strong>Solution 3: Monotonic Queue</strong></h1>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(k)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 70 ms
class MonotonicQueue {
public:
  void push(int e) {
    while(!data_.empty() &amp;&amp; e &gt; data_.back()) data_.pop_back();
    data_.push_back(e);
  } 
  
  void pop() {
    data_.pop_front();
  }
  
  int max() const { return data_.front(); }
private:
  deque&lt;int&gt; data_;
};

class Solution {
public:
  vector&lt;int&gt; maxSlidingWindow(vector&lt;int&gt;&amp; nums, int k) {
    MonotonicQueue q;
    vector&lt;int&gt; ans;
        
    for (int i = 0; i &lt; nums.size(); ++i) {
      q.push(nums[i]);
      if (i - k + 1 &gt;= 0) {
        ans.push_back(q.max());
        if (nums[i - k + 1] == q.max()) q.pop();
      }      
    }
    return ans;
  }
};</pre><p></div><h2 class="tabtitle">C++ V2</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 65 ms
class Solution {
public:
  vector&lt;int&gt; maxSlidingWindow(vector&lt;int&gt;&amp; nums, int k) {
    deque&lt;int&gt; index;
    vector&lt;int&gt; ans;
        
    for (int i = 0; i &lt; nums.size(); ++i) {
      while (!index.empty() &amp;&amp; nums[i] &gt;= nums[index.back()]) index.pop_back();
      index.push_back(i);      
      if (i - k + 1 &gt;= 0) ans.push_back(nums[index.front()]);
      if (i - k + 1 &gt;= index.front()) index.pop_front();
    }
    return ans;
  }
};</pre><p></div><h2 class="tabtitle">C++ V3</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 67 ms
class Solution {
public:
  vector&lt;int&gt; maxSlidingWindow(vector&lt;int&gt;&amp; nums, int k) {
    deque&lt;int&gt; q;
    vector&lt;int&gt; ans;
        
    for (int i = 0; i &lt; nums.size(); ++i) {
      while (!q.empty() &amp;&amp; nums[i] &gt; q.back()) q.pop_back();
      q.push_back(nums[i]);
      const int s = i - k + 1;
      if (s &lt; 0) continue;      
      ans.push_back(q.front());
      if (nums[s] == q.front()) q.pop_front();
    }
    return ans;
  }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 19 ms
class Solution {
  public int[] maxSlidingWindow(int[] nums, int k) {
    if (k == 0) return nums;
    
    int[] ans = new int[nums.length - k + 1];
    Deque&lt;Integer&gt; indices = new LinkedList&lt;&gt;();
    
    for (int i = 0; i &lt; nums.length; ++i) {
      while (indices.size() &gt; 0 &amp;&amp; nums[i] &gt;= nums[indices.getLast()])
        indices.removeLast();
      
      indices.addLast(i);
      if (i - k + 1 &gt;= 0) ans[i - k + 1] = nums[indices.getFirst()];
      if (i - k + 1 &gt;= indices.getFirst()) indices.removeFirst();
    }
             
    return ans;
  }
}</pre><p></div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 238 ms
"""
class MaxQueue:
  def __init__(self):
    self.q_ = collections.deque()
  
  def push(self, e):
    while self.q_ and e &gt; self.q_[-1]: self.q_.pop()
    self.q_.append(e)
  
  def pop(self):
    self.q_.popleft()
  
  def max(self):
    return self.q_[0]
    
class Solution:
  def maxSlidingWindow(self, nums, k):
    q = MaxQueue()
    ans = []
    for i in range(len(nums)):
      q.push(nums[i])
      if i &gt;= k - 1: 
        ans.append(q.max())
        if nums[i - k + 1] == q.max(): q.pop()
    return ans</pre><p></div><h2 class="tabtitle">Python3 V2</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 193 ms
"""
class Solution:
  def maxSlidingWindow(self, nums, k):
    indices = collections.deque()
    ans = []
    for i in range(len(nums)):
      while indices and nums[i] &gt;= nums[indices[-1]]: indices.pop()
      indices.append(i)
      if i &gt;= k - 1: ans.append(nums[indices[0]])
      if i - k + 1 == indices[0]: indices.popleft()
    return ans</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/heap/leetcode-239-sliding-window-maximum/">花花酱 LeetCode 239. Sliding Window Maximum</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/heap/leetcode-239-sliding-window-maximum/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
