<?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>fast slow Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/fast-slow/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/fast-slow/</link>
	<description></description>
	<lastBuildDate>Mon, 06 Dec 2021 03:19:05 +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>fast slow Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/fast-slow/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 202. Happy Number</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-202-happy-number/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-202-happy-number/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 06 Dec 2021 03:18:33 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[cycle]]></category>
		<category><![CDATA[fast slow]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9043</guid>

					<description><![CDATA[<p>Write an algorithm to determine if a number&#160;n&#160;is happy. A&#160;happy number&#160;is a number defined by the following process: Starting with any positive integer, replace the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-202-happy-number/">花花酱 LeetCode 202. Happy Number</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Write an algorithm to determine if a number&nbsp;<code>n</code>&nbsp;is happy.</p>



<p>A&nbsp;<strong>happy number</strong>&nbsp;is a number defined by the following process:</p>



<ul><li>Starting with any positive integer, replace the number by the sum of the squares of its digits.</li><li>Repeat the process until the number equals 1 (where it will stay), or it&nbsp;<strong>loops endlessly in a cycle</strong>&nbsp;which does not include 1.</li><li>Those numbers for which this process&nbsp;<strong>ends in 1</strong>&nbsp;are happy.</li></ul>



<p>Return&nbsp;<code>true</code>&nbsp;<em>if</em>&nbsp;<code>n</code>&nbsp;<em>is a happy number, and</em>&nbsp;<code>false</code>&nbsp;<em>if not</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 19
<strong>Output:</strong> true
<strong>Explanation:</strong>
1<sup>2</sup> + 9<sup>2</sup> = 82
8<sup>2</sup> + 2<sup>2</sup> = 68
6<sup>2</sup> + 8<sup>2</sup> = 100
1<sup>2</sup> + 0<sup>2</sup> + 0<sup>2</sup> = 1
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 2
<strong>Output:</strong> false
</pre>



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



<ul><li><code>1 &lt;= n &lt;= 2<sup>31</sup>&nbsp;- 1</code></li></ul>



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



<p>We can use a hasthable to store all the number we generated so far.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  bool isHappy(int n) {
    auto getNext = [](int x) -&gt; int {
      int ans = 0;
      while (x) {
        ans += (x % 10) * (x % 10);
        x /= 10;
      }
      return ans;
    };
    
    unordered_set&lt;int&gt; s;
    while (n != 1) {
      if (!s.insert(n).second) return false;
      n = getNext(n);
    }
    return true;
  }
};</pre>
</div></div>



<h2><strong>Optimization: Space reduction</strong></h2>



<p>Since the number sequence always has a cycle, we can use slow / fast pointers to detect the cycle without using a hastable.</p>



<p>Time complexity: O(L)<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:
  bool isHappy(int n) {
    auto getNext = [](int x) -&amp;gt; int {
      int ans = 0;
      while (x) {
        ans += (x % 10) * (x % 10);
        x /= 10;
      }
      return ans;
    };
    
    int slow = n;
    int fast = getNext(n);
    do {      
      slow = getNext(slow);
      fast = getNext(getNext(fast));
    } while (slow != fast);
    return slow == 1;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-202-happy-number/">花花酱 LeetCode 202. Happy 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/simulation/leetcode-202-happy-number/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2095. Delete the Middle Node of a Linked List</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-2095-delete-the-middle-node-of-a-linked-list/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-2095-delete-the-middle-node-of-a-linked-list/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 05 Dec 2021 06:24:18 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[fast slow]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[middle]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9020</guid>

					<description><![CDATA[<p>You are given the&#160;head&#160;of a linked list.&#160;Delete&#160;the&#160;middle node, and return&#160;the&#160;head&#160;of the modified linked list. The&#160;middle node&#160;of a linked list of size&#160;n&#160;is the&#160;⌊n / 2⌋th&#160;node from&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-2095-delete-the-middle-node-of-a-linked-list/">花花酱 LeetCode 2095. Delete the Middle Node of a Linked List</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>You are given the&nbsp;<code>head</code>&nbsp;of a linked list.&nbsp;<strong>Delete</strong>&nbsp;the&nbsp;<strong>middle node</strong>, and return&nbsp;<em>the</em>&nbsp;<code>head</code>&nbsp;<em>of the modified linked list</em>.</p>



<p>The&nbsp;<strong>middle node</strong>&nbsp;of a linked list of size&nbsp;<code>n</code>&nbsp;is the&nbsp;<code>⌊n / 2⌋<sup>th</sup></code>&nbsp;node from the&nbsp;<strong>start</strong>&nbsp;using&nbsp;<strong>0-based indexing</strong>, where&nbsp;<code>⌊x⌋</code>&nbsp;denotes the largest integer less than or equal to&nbsp;<code>x</code>.</p>



<ul><li>For&nbsp;<code>n</code>&nbsp;=&nbsp;<code>1</code>,&nbsp;<code>2</code>,&nbsp;<code>3</code>,&nbsp;<code>4</code>, and&nbsp;<code>5</code>, the middle nodes are&nbsp;<code>0</code>,&nbsp;<code>1</code>,&nbsp;<code>1</code>,&nbsp;<code>2</code>, and&nbsp;<code>2</code>, respectively.</li></ul>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/11/16/eg1drawio.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [1,3,4,7,1,2,6]
<strong>Output:</strong> [1,3,4,1,2,6]
<strong>Explanation:</strong>
The above figure represents the given linked list. The indices of the nodes are written below.
Since n = 7, node 3 with value 7 is the middle node, which is marked in red.
We return the new list after removing this node. 
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/11/16/eg2drawio.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [1,2,3,4]
<strong>Output:</strong> [1,2,4]
<strong>Explanation:</strong>
The above figure represents the given linked list.
For n = 4, node 2 with value 3 is the middle node, which is marked in red.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/11/16/eg3drawio.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [2,1]
<strong>Output:</strong> [2]
<strong>Explanation:</strong>
The above figure represents the given linked list.
For n = 2, node 1 with value 1 is the middle node, which is marked in red.
Node 0 with value 2 is the only node remaining after removing node 1.</pre>



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



<ul><li>The number of nodes in the list is in the range&nbsp;<code>[1, 10<sup>5</sup>]</code>.</li><li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li></ul>



<h2><strong>Solution: Fast / Slow pointers</strong></h2>



<p>Use fast / slow pointers to find the previous node of the middle one, then skip the middle one.</p>



<p>prev.next = prev.next.next</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">class Solution {
public:
  ListNode* deleteMiddle(ListNode* head) {
    ListNode dummy(0, head);
    ListNode* prev = &amp;dummy;
    ListNode* fast = head;
    // prev points to the previous node of the middle one.
    while (fast &amp;&amp; fast-&gt;next) {
      prev = prev-&gt;next;
      fast = fast-&gt;next-&gt;next;
    }    
    prev-&gt;next = prev-&gt;next-&gt;next;
    return dummy.next;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-2095-delete-the-middle-node-of-a-linked-list/">花花酱 LeetCode 2095. Delete the Middle Node of a Linked List</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/list/leetcode-2095-delete-the-middle-node-of-a-linked-list/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 143. Reorder List</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-143-reorder-list/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-143-reorder-list/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 29 Nov 2021 07:08:40 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[fast slow]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[reverse]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8926</guid>

					<description><![CDATA[<p>You are given the head of a singly linked-list. The list can be represented as: L0 → L1 → … → Ln - 1 →&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-143-reorder-list/">花花酱 LeetCode 143. Reorder List</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>You are given the head of a singly linked-list. The list can be represented as:</p>



<pre class="wp-block-preformatted;crayon:false">L<sub>0</sub> → L<sub>1</sub> → … → L<sub>n - 1</sub> → L<sub>n</sub>
</pre>



<p><em>Reorder the list to be on the following form:</em></p>



<pre class="wp-block-preformatted;crayon:false">L<sub>0</sub> → L<sub>n</sub> → L<sub>1</sub> → L<sub>n - 1</sub> → L<sub>2</sub> → L<sub>n - 2</sub> → …
</pre>



<p>You may not modify the values in the list&#8217;s nodes. Only nodes themselves may be changed.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/03/04/reorder1linked-list.jpg" alt=""/></figure>



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



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/03/09/reorder2-linked-list.jpg" alt=""/></figure>



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



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



<ul><li>The number of nodes in the list is in the range&nbsp;<code>[1, 5 * 10<sup>4</sup>]</code>.</li><li><code>1 &lt;= Node.val &lt;= 1000</code></li></ul>



<h2><strong>Solution: Three steps</strong></h2>



<p>Step 1: Find mid node that splits the list into two halves.<br>Step 2: Reverse the second half<br>Step 3: Merge two lists</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:
  void reorderList(ListNode* head) {
    if (!head || !head-&gt;next) return;
    ListNode* slow = head;
    ListNode* fast = head;            

    while (fast-&gt;next &amp;&amp; fast-&gt;next-&gt;next) {
      slow = slow-&gt;next;
      fast = fast-&gt;next-&gt;next;          
    }
    
    ListNode* h1 = head;
    ListNode* h2 = reverse(slow-&gt;next);
    slow-&gt;next = nullptr;

    while (h1 &amp;&amp; h2) {
      ListNode* n1 = h1-&gt;next;
      ListNode* n2 = h2-&gt;next;
      h1-&gt;next = h2;
      h2-&gt;next = n1;
      h1 = n1;
      h2 = n2;
    }
  }
private:       
  // reverse a linked list
  // returns head of the linked list
  ListNode* reverse(ListNode* head) {
    if (!head || !head-&gt;next) return head;

    ListNode* prev = head;
    ListNode* cur = head-&gt;next;
    ListNode* next = cur;
    while (cur) {
      next = next-&gt;next;
      cur-&gt;next = prev;
      prev = cur;
      cur = next;
    }

    head-&gt;next = nullptr;
    return prev;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-143-reorder-list/">花花酱 LeetCode 143. Reorder List</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/list/leetcode-143-reorder-list/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 19. Remove Nth Node From End of List</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-19-remove-nth-node-from-end-of-list/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-19-remove-nth-node-from-end-of-list/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 20 Sep 2018 06:54:23 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[dummy head]]></category>
		<category><![CDATA[fast slow]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[node]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4057</guid>

					<description><![CDATA[<p>Problem Given a linked list, remove the n-th node from the end of list and return its head. Example: Given linked list: 1-&#62;2-&#62;3-&#62;4-&#62;5, and n =&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-19-remove-nth-node-from-end-of-list/">花花酱 LeetCode 19. Remove Nth Node From End of List</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>Given a linked list, remove the <em>n</em>-th node from the end of list and return its head.</p>
<p><strong>Example:</strong></p>
<pre class="crayon:false">Given linked list: <strong>1-&gt;2-&gt;3-&gt;4-&gt;5</strong>, and <strong><em>n</em> = 2</strong>.

After removing the second node from the end, the linked list becomes <strong>1-&gt;2-&gt;3-&gt;5</strong>.
</pre>
<p><strong>Note:</strong></p>
<p>Given <em>n</em> will always be valid.</p>
<p><strong>Follow up:</strong></p>
<p>Could you do this in one pass?</p>
<h1>Solution 0: Cheating! store the nodes in an array</h1>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  ListNode *removeNthFromEnd(ListNode *head, int n) {
    if (!head) return nullptr;
    vector&lt;ListNode *&gt; nodes;
    ListNode *cur = head;
    while (cur) {
      nodes.push_back(cur);
      cur = cur-&gt;next;
    }
    if (n == nodes.size()) return head-&gt;next;
    ListNode* nodes_to_remove = nodes[nodes.size()-n];
    ListNode* parent = nodes[nodes.size() - n - 1];
    parent-&gt;next = nodes_to_remove-&gt;next;
    delete nodes_to_remove;
    return head;
  }
};</pre><p></div></div></p>
<h1>Solution 1: Two passes</h1>
<p>Time complexity: O(L)</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
class Solution {
public:
  ListNode* removeNthFromEnd(ListNode* head, int n) {
    int l = 0;
    ListNode* cur = head;
    while (cur) {
      ++l;
      cur = cur-&gt;next;
    }
    if (n == l) {
      ListNode* ans = head-&gt;next;
      delete head;
      return ans;
    }    
    l -= n;
    cur = head;
    while (--l) cur = cur-&gt;next;
    ListNode* node = cur-&gt;next;
    cur-&gt;next = node-&gt;next;
    delete node;
    return head;
  }
};</pre><p></div></div></p>
<h1><strong>Solution 2: Fast/Slow Pointers + Dummy Head / Prev</strong></h1>
<p>Fast pointer moves n steps first, and then slow pointer starts moving.</p>
<p>When fast pointer reaches tail, slow pointer is n-th node from the end.</p>
<p>Time complexity: O(L)</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
class Solution {
public:
  ListNode* removeNthFromEnd(ListNode* head, int n) {
    ListNode* fast = head;
    for (int i = 0; i &lt; n; ++i) 
      fast = fast-&gt;next;
    ListNode dummy(0);
    dummy.next = head;
    ListNode* prev = &amp;dummy;
    while (fast) {
      fast = fast-&gt;next;
      prev = prev-&gt;next;
    }
    ListNode* node = prev-&gt;next;
    prev-&gt;next = node-&gt;next;
    delete node;
    return dummy.next;
  }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
  public ListNode removeNthFromEnd(ListNode head, int n) {
    ListNode dummy = new ListNode(0);
    dummy.next = head;
    ListNode fast = head;
    while (n-- &gt; 0) fast = fast.next;
    ListNode prev = dummy;
    while (fast != null) {
      fast = fast.next;
      prev = prev.next;
    }
    prev.next = prev.next.next;
    return dummy.next;
  }
}</pre><p></div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def removeNthFromEnd(self, head, n):
    dummy = ListNode(0)
    dummy.next = head
    fast, prev = head, dummy
    for _ in range(n): 
      fast = fast.next
    while fast:
      fast, prev = fast.next, prev.next
    prev.next = prev.next.next
    return dummy.next</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-19-remove-nth-node-from-end-of-list/">花花酱 LeetCode 19. Remove Nth Node From End of List</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/list/leetcode-19-remove-nth-node-from-end-of-list/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 141. Linked List Cycle</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-141-linked-list-cycle/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-141-linked-list-cycle/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 24 Aug 2018 16:18:07 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[cycle]]></category>
		<category><![CDATA[fast slow]]></category>
		<category><![CDATA[list]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3683</guid>

					<description><![CDATA[<p>Problem Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using extra space? Solution1: HashTable&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-141-linked-list-cycle/">花花酱 LeetCode 141. Linked List Cycle</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/bxCb37nLXWM?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<h1><strong>Problem</strong></h1>
<div class="question-description__3U1T">
<div>
<p>Given a linked list, determine if it has a cycle in it.</p>
<p>Follow up:<br />
Can you solve it without using extra space?</p>
<h1><strong>Solution1: HashTable</strong></h1>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(n)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 16 ms
class Solution {
public:
  bool hasCycle(ListNode *head) {
    unordered_set&lt;ListNode*&gt; seen;
    while (head) {
      if (seen.count(head)) return true;
      seen.insert(head);
      head = head-&gt;next;
    }
    return false;
  }
};</pre><p>
</p></div>
</div>
<h1><strong>Solution2: Fast + Slow pointers</strong></h1>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(1)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 8 ms
class Solution {
public:
  bool hasCycle(ListNode *head) {
    auto slow = head;
    auto fast = head;
    while (fast) {
      if (!fast-&gt;next) return false;
      fast = fast-&gt;next-&gt;next;
      slow = slow-&gt;next;
      if (fast == slow) return true;
    }
    return false;
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-141-linked-list-cycle/">花花酱 LeetCode 141. Linked List Cycle</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/list/leetcode-141-linked-list-cycle/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 148. Sort List</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-148-sort-list/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-148-sort-list/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 27 Jul 2018 04:57:00 +0000</pubDate>
				<category><![CDATA[Divide and conquer]]></category>
		<category><![CDATA[List]]></category>
		<category><![CDATA[fast slow]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[mergesort]]></category>
		<category><![CDATA[sort]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3320</guid>

					<description><![CDATA[<p>Problem Sort a linked list in O(n log n) time using constant space complexity. Example 1: Input: 4-&#62;2-&#62;1-&#62;3 Output: 1-&#62;2-&#62;3-&#62;4 Example 2: Input: -1-&#62;5-&#62;3-&#62;4-&#62;0 Output: -1-&#62;0-&#62;3-&#62;4-&#62;5 Solution: Merge&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-148-sort-list/">花花酱 LeetCode 148. Sort List</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/M1TwY0nsTZA?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<h1><strong>Problem</strong></h1>
<p>Sort a linked list in <em>O</em>(<em>n</em> log <em>n</em>) time using constant space complexity.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false "><strong>Input:</strong> 4-&gt;2-&gt;1-&gt;3
<strong>Output:</strong> 1-&gt;2-&gt;3-&gt;4
</pre>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> -1-&gt;5-&gt;3-&gt;4-&gt;0
<strong>Output:</strong> -1-&gt;0-&gt;3-&gt;4-&gt;5</pre>
<p><img class="alignnone size-full wp-image-3330" style="font-size: 16px;" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/148-ep211.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/148-ep211.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/148-ep211-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/148-ep211-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /><img class="alignnone size-full wp-image-3329" style="font-size: 16px;" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/148-ep211-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/148-ep211-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/148-ep211-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/148-ep211-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<h1>Solution: Merge Sort</h1>
<p>Top-down (recursion)</p>
<p>Time complexity: O(nlogn)</p>
<p>Space complexity: O(logn)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 32 ms
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
  ListNode* sortList(ListNode* head) {
    // 0 or 1 element, we are done.
    if (!head || !head-&gt;next) return head;
    ListNode* slow = head;
    ListNode* fast = head-&gt;next;    
    while (fast &amp;&amp; fast-&gt;next) {
      fast = fast-&gt;next-&gt;next;
      slow = slow-&gt;next;
    }
    ListNode* mid = slow-&gt;next;    
    slow-&gt;next = nullptr; // Break the list.
    return merge(sortList(head), sortList(mid));
  }
private:
  ListNode* merge(ListNode* l1, ListNode* l2) {
    ListNode dummy(0);
    ListNode* tail = &amp;dummy;
    while (l1 &amp;&amp; l2) {
      if (l1-&gt;val &gt; l2-&gt;val) swap(l1, l2);
      tail-&gt;next = l1;
      l1 = l1-&gt;next;
      tail = tail-&gt;next;
    }
    tail-&gt;next = l1 ? l1 : l2;    
    return dummy.next;
  }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 6 ms
class Solution {
  public ListNode sortList(ListNode head) {
    if (head == null || head.next == null) return head;
    ListNode slow = head;
    ListNode fast = head.next;
    while (fast != null &amp;&amp; fast.next != null) {
      fast = fast.next.next;
      slow = slow.next;
    }
    ListNode mid = slow.next;
    slow.next = null;
    return merge(sortList(head), sortList(mid));
  }
  
  private ListNode merge(ListNode l1, ListNode l2) {
    ListNode dummy = new ListNode(0);
    ListNode tail = dummy;
    while (l1 != null &amp;&amp; l2 != null) {
      if (l1.val &gt; l2.val) {
        ListNode tmp = l1;
        l1 = l2;
        l2 = tmp;
      }
      tail.next = l1;
      l1 = l1.next;
      tail = tail.next;
    }
    tail.next = (l1 != null) ? l1 : l2;
    return dummy.next;
  }
}</pre><p></div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag"># Author: Huahua, 232 ms
class Solution:
  def sortList(self, head):
    def merge(l1, l2):
      dummy = ListNode(0)
      tail = dummy
      while l1 and l2:
        if l1.val &gt; l2.val: l1, l2 = l2, l1
        tail.next = l1
        l1 = l1.next
        tail = tail.next
      tail.next = l1 if l1 else l2
      return dummy.next
    
    if not head or not head.next: return head
    slow = head
    fast = head.next
    while fast and fast.next:
      fast = fast.next.next
      slow = slow.next
    mid = slow.next
    slow.next = None
    return merge(self.sortList(head), self.sortList(mid))</pre><p>&nbsp;</p>
<p></div></div></p>
<p>bottom up</p>
<p>Time complexity: O(nlogn)</p>
<p>Space complexity: O(1)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 32 ms
class Solution {
public:
  ListNode* sortList(ListNode* head) {
    // 0 or 1 element, we are done.
    if (!head || !head-&gt;next) return head;
    
    int len = 1;
    ListNode* cur = head;
    while (cur = cur-&gt;next) ++len;
    
    ListNode dummy(0);
    dummy.next = head;
    ListNode* l;
    ListNode* r;
    ListNode* tail;
    for (int n = 1; n &lt; len; n &lt;&lt;= 1) {      
      cur = dummy.next; // partial sorted head
      tail = &amp;dummy;
      while (cur) {
        l = cur;
        r = split(l, n);
        cur = split(r, n);
        auto merged = merge(l, r);
        tail-&gt;next = merged.first;
        tail = merged.second;
      }
    }      
    return dummy.next;
  }
private:
  // Splits the list into two parts, first n element and the rest.
  // Returns the head of the rest.
  ListNode* split(ListNode* head, int n) {    
    while (--n &amp;&amp; head)
      head = head-&gt;next;
    ListNode* rest = head ? head-&gt;next : nullptr;
    if (head) head-&gt;next = nullptr;
    return rest;
  }
  
  // Merges two lists, returns the head and tail of the merged list.
  pair&lt;ListNode*, ListNode*&gt; merge(ListNode* l1, ListNode* l2) {
    ListNode dummy(0);
    ListNode* tail = &amp;dummy;
    while (l1 &amp;&amp; l2) {
      if (l1-&gt;val &gt; l2-&gt;val) swap(l1, l2);
      tail-&gt;next = l1;
      l1 = l1-&gt;next;
      tail = tail-&gt;next;
    }
    tail-&gt;next = l1 ? l1 : l2;
    while (tail-&gt;next) tail = tail-&gt;next;
    return {dummy.next, tail};
  }
};</pre><p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-148-sort-list/">花花酱 LeetCode 148. Sort List</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/list/leetcode-148-sort-list/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
