<?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>merge Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/merge/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/merge/</link>
	<description></description>
	<lastBuildDate>Wed, 02 Mar 2022 14:52:52 +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>merge Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/merge/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2181. Merge Nodes in Between Zeros</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-2181-merge-nodes-in-between-zeros/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-2181-merge-nodes-in-between-zeros/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 02 Mar 2022 14:51:51 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[merge]]></category>
		<category><![CDATA[skip]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9522</guid>

					<description><![CDATA[<p>You are given the&#160;head&#160;of a linked list, which contains a series of integers&#160;separated&#160;by&#160;0&#8216;s. The&#160;beginning&#160;and&#160;end&#160;of the linked list will have&#160;Node.val == 0. For&#160;every&#160;two consecutive&#160;0&#8216;s,&#160;merge&#160;all the nodes&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-2181-merge-nodes-in-between-zeros/">花花酱 LeetCode 2181. Merge Nodes in Between Zeros</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, which contains a series of integers&nbsp;<strong>separated</strong>&nbsp;by&nbsp;<code>0</code>&#8216;s. The&nbsp;<strong>beginning</strong>&nbsp;and&nbsp;<strong>end</strong>&nbsp;of the linked list will have&nbsp;<code>Node.val == 0</code>.</p>



<p>For&nbsp;<strong>every&nbsp;</strong>two consecutive&nbsp;<code>0</code>&#8216;s,&nbsp;<strong>merge</strong>&nbsp;all the nodes lying in between them into a single node whose value is the&nbsp;<strong>sum</strong>&nbsp;of all the merged nodes. The modified list should not contain any&nbsp;<code>0</code>&#8216;s.</p>



<p>Return&nbsp;<em>the</em>&nbsp;<code>head</code>&nbsp;<em>of the modified linked list</em>.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2022/02/02/ex1-1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [0,3,1,0,4,5,2,0]
<strong>Output:</strong> [4,11]
<strong>Explanation:</strong> 
The above figure represents the given linked list. The modified list contains
- The sum of the nodes marked in green: 3 + 1 = 4.
- The sum of the nodes marked in red: 4 + 5 + 2 = 11.
</pre>



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [0,1,0,3,0,2,2,0]
<strong>Output:</strong> [1,3,4]
<strong>Explanation:</strong> 
The above figure represents the given linked list. The modified list contains
- The sum of the nodes marked in green: 1 = 1.
- The sum of the nodes marked in red: 3 = 3.
- The sum of the nodes marked in yellow: 2 + 2 = 4.
</pre>



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



<ul><li>The number of nodes in the list is in the range&nbsp;<code>[3, 2 * 10<sup>5</sup>]</code>.</li><li><code>0 &lt;= Node.val &lt;= 1000</code></li><li>There are&nbsp;<strong>no</strong>&nbsp;two consecutive nodes with&nbsp;<code>Node.val == 0</code>.</li><li>The&nbsp;<strong>beginning</strong>&nbsp;and&nbsp;<strong>end</strong>&nbsp;of the linked list have&nbsp;<code>Node.val == 0</code>.</li></ul>



<h2><strong>Solution: List</strong></h2>



<p>Skip the first zero, replace every zero node with the sum of values of its previous nodes.</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:
  ListNode* mergeNodes(ListNode* head) {
    ListNode dummy;    
    head = head-&gt;next;
    for (ListNode* prev = &amp;dummy; head; head = head-&gt;next) {
      int sum = 0;
      while (head-&gt;val != 0) {
        sum += head-&gt;val;
        head = head-&gt;next;
      }
      prev-&gt;next = head;
      head-&gt;val = sum;
      prev = head;      
    }
    return dummy.next;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-2181-merge-nodes-in-between-zeros/">花花酱 LeetCode 2181. Merge Nodes in Between Zeros</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-2181-merge-nodes-in-between-zeros/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 959. Regions Cut By Slashes</title>
		<link>https://zxi.mytechroad.com/blog/graph/leetcode-959-regions-cut-by-slashes/</link>
					<comments>https://zxi.mytechroad.com/blog/graph/leetcode-959-regions-cut-by-slashes/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 19 Dec 2018 03:08:57 +0000</pubDate>
				<category><![CDATA[Graph]]></category>
		<category><![CDATA[geometry]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[merge]]></category>
		<category><![CDATA[union find]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4484</guid>

					<description><![CDATA[<p>In a N x N&#160;grid&#160;composed of 1 x 1 squares, each 1 x 1 square consists of a&#160;/,&#160;\, or blank space.&#160; These characters divide the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-959-regions-cut-by-slashes/">花花酱 LeetCode 959. Regions Cut By Slashes</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<iframe width="500" height="375" src="https://www.youtube.com/embed/n3s9Q7GtfB4?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>



<p>In a N x N&nbsp;<code>grid</code>&nbsp;composed of 1 x 1 squares, each 1 x 1 square consists of a&nbsp;<code>/</code>,&nbsp;<code>\</code>, or blank space.&nbsp; These characters divide the square into contiguous regions.</p>



<p>(Note that backslash characters are escaped, so a&nbsp;<code>\</code>&nbsp;is represented as&nbsp;<code>"\\"</code>.)</p>



<p>Return the number of regions.</p>



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



<pre class="wp-block-preformatted crayon:false"><strong>Input:</strong>[&nbsp; " /",&nbsp; "/ "]<br><strong>Output: </strong>2<br><strong>Explanation: </strong>The 2x2 grid is as follows:</pre>



<img src="https://assets.leetcode.com/uploads/2018/12/15/1.png">



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



<pre class="wp-block-preformatted crayon:false"><strong>Input:</strong>[&nbsp; " /",&nbsp; "  "]<br><strong>Output: </strong>1<br><strong>Explanation: </strong>The 2x2 grid is as follows:</pre>



<img src="https://assets.leetcode.com/uploads/2018/12/15/2.png">



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



<pre class="wp-block-preformatted crayon:false"><strong>Input:</strong>[&nbsp; "\\/",&nbsp; "/\\"]<br><strong>Output: </strong>4<br><strong>Explanation: </strong>(Recall that because \ characters are escaped, "\\/" refers to \/, and "/\\" refers to /\.)The 2x2 grid is as follows:</pre>



<img src="https://assets.leetcode.com/uploads/2018/12/15/3.png">



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



<pre class="wp-block-preformatted crayon:false"><strong>Input:</strong>[&nbsp; "/\\",&nbsp; "\\/"]<br><strong>Output: </strong>5<br><strong>Explanation: </strong>(Recall that because \ characters are escaped, "/\\" refers to /\, and "\\/" refers to \/.)The 2x2 grid is as follows:</pre>



<img src="https://assets.leetcode.com/uploads/2018/12/15/4.png">



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



<pre class="wp-block-preformatted crayon:false"><strong>Input:</strong>[&nbsp; "//",&nbsp; "/ "]<br><strong>Output: </strong>3<br><strong>Explanation: </strong>The 2x2 grid is as follows:</pre>



<img src="https://assets.leetcode.com/uploads/2018/12/15/5.png">



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



<ol><li><code>1 &lt;= grid.length == grid[0].length &lt;= 30</code></li><li><code>grid[i][j]</code>&nbsp;is either&nbsp;<code>'/'</code>,&nbsp;<code>'\'</code>, or&nbsp;<code>' '</code>.</li></ol>



<h1><strong>Solution 1: Split grid into 4 triangles and Union Find Faces</strong></h1>



<figure class="wp-block-image"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/959-ep235-1.png" alt="" class="wp-image-4496" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/959-ep235-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/959-ep235-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/959-ep235-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<p>Divide each grid into 4 triangles and union them if not split.<br>Time complexity: O(n^2*alphn(n^2))<br>Space complexity: O(n^2)</p>



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

<pre class="crayon-plain-tag">class Solution {  
public:
  int regionsBySlashes(vector&lt;string&gt;&amp; grid) {
    int n = grid.size();    
    DSU dsu(4 * n * n);
    for (int r = 0; r &lt; n; ++r)
      for (int c = 0; c &lt; n; ++c) {
        int index = 4 * (r * n + c);
        switch (grid[r][c]) {
          case '/':
            dsu.merge(index + 0, index + 3);
            dsu.merge(index + 1, index + 2);
            break;
          case '\\':
            dsu.merge(index + 0, index + 1);
            dsu.merge(index + 2, index + 3);
            break;
          case ' ':
            dsu.merge(index + 0, index + 1);
            dsu.merge(index + 1, index + 2);
            dsu.merge(index + 2, index + 3);
            break;
          default: break;
        }
        if (r + 1 &lt; n)
          dsu.merge(index + 2, index + 4 * n + 0);
        if (c + 1 &lt; n)
          dsu.merge(index + 1, index + 4 + 3);
      }
    int ans = 0;
    for (int i = 0; i &lt; 4 * n * n; ++i)
      if (dsu.find(i) == i) ++ans;
    return ans;
  }
private:
  class DSU {
    public:
      DSU(int n): parent_(n) {
        for (int i = 0; i &lt; n; ++i)
          parent_[i] = i;
      }
      
      int find(int x) {
        if (parent_[x] != x) parent_[x] = find(parent_[x]);
        return parent_[x];
      }
      
      void merge(int x, int y) {
        parent_[find(x)] = find(y);
      }
    private:
      vector&lt;int&gt; parent_;
  };
};</pre>
</div></div>



<h1><br><strong>Solution 2: Euler&#8217;s Formula / Union-Find vertices</strong></h1>



<figure class="wp-block-image"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/959-ep235-2.png" alt="" class="wp-image-4497" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/959-ep235-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/959-ep235-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/959-ep235-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



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

<pre class="crayon-plain-tag">class Solution {  
public:
  int regionsBySlashes(vector&lt;string&gt;&amp; grid) {
    int n = grid.size();
    p_ = vector&lt;int&gt;((n + 1) * (n + 1));     
    // All vertices on the boundaries are merged into root(0).    
    for (int r = 0; r &lt; n + 1; ++r)
      for (int c = 0; c &lt; n + 1; ++c)
        p_[getIndex(n, r, c)] = (r == 0 || r == n || c == 0 || c == n) ? 0 : getIndex(n, r, c);
    
    int f = 1;    
    for (int r = 0; r &lt; n; ++r)
      for (int c = 0; c &lt; n; ++c) {
        if (grid[r][c] == ' ') continue;
        // A new face will created if two vertices are already in the same group.        
        if (grid[r][c] == '/') {
          f += merge(getIndex(n, r, c + 1),
                     getIndex(n, r + 1, c));
        } else {
          f += merge(getIndex(n, r, c),
                     getIndex(n, r + 1, c + 1));
        }
      }    
    return f;
  }
private:
  vector&lt;int&gt; p_;  
  
  int getIndex(int n, int r, int c) { return r * (n + 1) + c; }  
      
  int find(int x) {
    if (p_[x] != x) p_[x] = find(p_[x]);
      return p_[x];
  }
  
  int merge(int x, int y) {
    int rx = find(x);
    int ry = find(y);
    if (rx == ry) return 1;
    p_[ry] = rx;
    return 0;
  }
};</pre>
</div></div>



<h1 id="mce_0"><strong>Solution 3: Pixelation (Upscale 3 times) </strong></h1>



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



<figure class="wp-block-image"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/959-ep235-3.png" alt="" class="wp-image-4519" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/959-ep235-3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/959-ep235-3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/959-ep235-3-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



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

<pre class="crayon-plain-tag">// Author: Huahua, running time: 20 ms
class Solution {
public:
  int regionsBySlashes(vector&lt;string&gt;&amp; grid) {
    const int n = grid.size();
    vector&lt;vector&lt;int&gt;&gt; g(n * 3, vector&lt;int&gt;(n * 3));
    for (int i = 0; i &lt; n; ++i)
      for (int j = 0; j &lt; n; ++j) {
        if (grid[i][j] == '/') {
          g[i * 3 + 0][j * 3 + 2] = 1;
          g[i * 3 + 1][j * 3 + 1] = 1;
          g[i * 3 + 2][j * 3 + 0] = 1;
        } else if (grid[i][j] == '\\') {
          g[i * 3 + 0][j * 3 + 0] = 1;
          g[i * 3 + 1][j * 3 + 1] = 1;
          g[i * 3 + 2][j * 3 + 2] = 1;
        }
      }
    int ans = 0;
    for (int i = 0; i &lt; 3 * n; ++i)
      for (int j = 0; j &lt; 3 * n; ++j) {
        if (g[i][j]) continue;
        visit(g, j, i, n * 3);
        ++ans;
      }
    return ans;
  }
private:
  void visit(vector&lt;vector&lt;int&gt;&gt;&amp; g, int x, int y, int n) {
    if (x &lt; 0 || x &gt;= n || y &lt; 0 || y &gt;= n) return;
    if (g[y][x]) return;
    g[y][x] = 1;
    visit(g, x + 1, y, n);
    visit(g, x, y + 1, n);
    visit(g, x - 1, y, n);
    visit(g, x, y - 1, n);
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-959-regions-cut-by-slashes/">花花酱 LeetCode 959. Regions Cut By Slashes</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-959-regions-cut-by-slashes/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 23. Merge k Sorted Lists</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-23-merge-k-sorted-lists/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-23-merge-k-sorted-lists/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 02 Oct 2018 08:02:55 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[merge]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4117</guid>

					<description><![CDATA[<p>Problem Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Example: Input: [   1-&#62;4-&#62;5,   1-&#62;3-&#62;4,   2-&#62;6&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-23-merge-k-sorted-lists/">花花酱 LeetCode 23. Merge k Sorted Lists</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>Merge <em>k</em> sorted linked lists and return it as one sorted list. Analyze and describe its complexity.</p>
<p><strong>Example:</strong></p>
<pre class="crayon:false"><strong>Input:</strong>
[
  1-&gt;4-&gt;5,
  1-&gt;3-&gt;4,
  2-&gt;6
]
<strong>Output:</strong> 1-&gt;1-&gt;2-&gt;3-&gt;4-&gt;4-&gt;5-&gt;6</pre>
<h1><strong>Solution 1: Brute Force</strong></h1>
<p>Time complexity: O(nk)</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, 420 ms
class Solution {
public:
  ListNode* mergeKLists(vector&lt;ListNode*&gt;&amp; lists) {
    ListNode dummy(0);
    ListNode *cur = &amp;dummy;
    while (true) {
      ListNode** min_head = nullptr;
      for (auto&amp; head : lists) {          
        if (!head) continue;        
        if (!min_head || head-&gt;val &lt; (*min_head)-&gt;val)
          min_head = &amp;head;
      }
      if (!min_head) break;
      cur-&gt;next = new ListNode((*min_head)-&gt;val);
      cur = cur-&gt;next;
      *min_head = (*min_head)-&gt;next;      
    }
    return dummy.next;
  }
};</pre><p></div></div></p>
<h1><strong>Solution 2: Heap / Priority Queue</strong></h1>
<p>Time complexity: O(nlogk)</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, 16 ms (&lt;99.88%)
class Solution {
public:
  ListNode* mergeKLists(vector&lt;ListNode*&gt;&amp; lists) {
    ListNode dummy(0);
    ListNode *cur = &amp;dummy;
    
    auto comp = [](ListNode* a, ListNode* b) { return a-&gt;val &gt; b-&gt;val; };
    priority_queue&lt;ListNode*, vector&lt;ListNode*&gt;, decltype(comp)&gt; q(comp);
    
    for (ListNode* list : lists) 
      if (list) q.push(list);
    
    while (!q.empty()) {
      cur-&gt;next = q.top(); q.pop();      
      cur = cur-&gt;next;
      if (cur-&gt;next) q.push(cur-&gt;next);
    }
    return dummy.next;
  }
};</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-23-merge-k-sorted-lists/">花花酱 LeetCode 23. Merge k Sorted Lists</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-23-merge-k-sorted-lists/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 88. Merge Sorted Array</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-88-merge-sorted-array/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-88-merge-sorted-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 28 Sep 2018 02:48:53 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[merge]]></category>
		<category><![CDATA[sort]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4083</guid>

					<description><![CDATA[<p>Problem Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has enough space (size that&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-88-merge-sorted-array/">花花酱 LeetCode 88. Merge Sorted Array</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>Given two sorted integer arrays <em>nums1</em> and <em>nums2</em>, merge <em>nums2</em> into <em>nums1</em> as one sorted array.</p>
<p><strong>Note:</strong></p>
<ul>
<li>The number of elements initialized in <em>nums1</em> and <em>nums2</em> are <em>m</em> and <em>n</em> respectively.</li>
<li>You may assume that <em>nums1</em> has enough space (size that is greater or equal to <em>m</em> + <em>n</em>) to hold additional elements from <em>nums2</em>.</li>
</ul>
<p><strong>Example:</strong></p>
<pre class="crayon:false"><strong>Input:</strong>
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6],       n = 3

<strong>Output:</strong> [1,2,2,3,5,6]
</pre>
<h1><strong>Solution:</strong></h1>
<p>Fill nums1 from back to front</p>
<p>Time complexity: O(m + n)</p>
<p>Space complexity: O(1) in-place</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:
  void merge(vector&lt;int&gt;&amp; nums1, int m, vector&lt;int&gt;&amp; nums2, int n) {
    int i = m - 1;
    int j = n - 1;
    int tail = m + n - 1;
    while (j &gt;= 0)
      nums1[tail--] = (i &gt;= 0 &amp;&amp; nums1[i] &gt; nums2[j]) ? nums1[i--] : nums2[j--];    
  }
};</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-88-merge-sorted-array/">花花酱 LeetCode 88. Merge Sorted Array</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-88-merge-sorted-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 617. Merge Two Binary Trees</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-617-merge-two-binary-trees/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-617-merge-two-binary-trees/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 18 Aug 2018 06:44:25 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[merge]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3604</guid>

					<description><![CDATA[<p>Problem Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-617-merge-two-binary-trees/">花花酱 LeetCode 617. Merge Two Binary Trees</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/EmVsf2sMNiU?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<h1><strong>Problem</strong></h1>
<p>Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.</p>
<p>You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.</p>
<p><b>Example 1:</b></p>
<pre class="crayon:false "><b>Input:</b> 
	Tree 1                     Tree 2                  
          1                         2                             
         / \                       / \                            
        3   2                     1   3                        
       /                           \   \                      
      5                             4   7                  
<b>Output:</b> 
Merged tree:
	     3
	    / \
	   4   5
	  / \   \ 
	 5   4   7
</pre>
<p><b>Note:</b> The merging process must start from the root nodes of both trees.</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"><br />
</ins></p>
<h1><strong>Solution: Recursion</strong></h1>
<p>Reuse t1/t2</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 52 ms
class Solution {
public:
  TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
    if (t1 == nullptr) return t2;
    if (t2 == nullptr) return t1;

    auto root = t1;
    root-&gt;val += t2-&gt;val;
    root-&gt;left = mergeTrees(t1-&gt;left, t2-&gt;left);
    root-&gt;right = mergeTrees(t1-&gt;right, t2-&gt;right);

    return root;
  }
};</pre><p>Create a copy</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 52 ms
class Solution {
public:
  TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
    if (t1 == nullptr) return copyTree(t2);
    if (t2 == nullptr) return copyTree(t1);

    TreeNode* root = new TreeNode(t1-&gt;val + t2-&gt;val);    
    root-&gt;left = mergeTrees(t1-&gt;left, t2-&gt;left);
    root-&gt;right = mergeTrees(t1-&gt;right, t2-&gt;right);

    return root;
  }
private:
  TreeNode* copyTree(TreeNode* root) {
    if (root == nullptr) return nullptr;
    TreeNode* r = new TreeNode(root-&gt;val);
    r-&gt;left = copyTree(root-&gt;left);
    r-&gt;right = copyTree(root-&gt;right);
    return r;
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-617-merge-two-binary-trees/">花花酱 LeetCode 617. Merge Two Binary Trees</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-617-merge-two-binary-trees/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 57. Insert Interval</title>
		<link>https://zxi.mytechroad.com/blog/geometry/leetcode-57-insert-interval/</link>
					<comments>https://zxi.mytechroad.com/blog/geometry/leetcode-57-insert-interval/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 15 Oct 2017 04:58:15 +0000</pubDate>
				<category><![CDATA[Geometry]]></category>
		<category><![CDATA[interval]]></category>
		<category><![CDATA[merge]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=586</guid>

					<description><![CDATA[<p>Problem: Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that the intervals were initially sorted according&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/geometry/leetcode-57-insert-interval/">花花酱 LeetCode 57. Insert Interval</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/oWHWDI2eOHY?feature=oembed" frameborder="0" gesture="media" allowfullscreen></iframe></p>
<p><strong>Problem:</strong></p>
<div class="question-description">
<p>Given a set of <i>non-overlapping</i> intervals, insert a new interval into the intervals (merge if necessary).</p>
<p>You may assume that the intervals were initially sorted according to their start times.</p>
<p><b>Example 1:</b><br />
Given intervals <code>[1,3],[6,9]</code>, insert and merge <code>[2,5]</code> in as <code>[1,5],[6,9]</code>.</p>
<p><b>Example 2:</b><br />
Given <code>[1,2],[3,5],[6,7],[8,10],[12,16]</code>, insert and merge <code>[4,9]</code> in as <code>[1,2],[3,10],[12,16]</code>.</p>
<p>This is because the new interval <code>[4,9]</code> overlaps with <code>[3,5],[6,7],[8,10].</code></p>
<p><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><br />
<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><br />
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<p><strong>Idea:</strong></p>
<p>Find the position of the new interval, insert it into the list and call MergeIntervals in <a href="http://zxi.mytechroad.com/blog/geometry/leetcode-56-merge-intervals/">LeetCode 56</a></p>
</div>
<p><strong>Solution:</strong></p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 16 ms
class Solution {
public:
    vector&lt;Interval&gt; insert(vector&lt;Interval&gt;&amp; intervals, Interval newInterval) {
        auto it = intervals.begin();
        while (it != intervals.end() &amp;&amp; newInterval.start &gt; it-&gt;start) ++it;
        intervals.insert(it, newInterval);
        
        // Merge intervals without sorting
        vector&lt;Interval&gt; ans;        
        for (const auto&amp; interval : intervals) {
            if (ans.empty() || interval.start &gt; ans.back().end) {
                ans.push_back(interval);
            } else {
                ans.back().end = max(ans.back().end, interval.end);
            }
        }
        
        return ans;
    }
};</pre><p>&nbsp;</p>
<p>Python</p><pre class="crayon-plain-tag">"""
Author: Huahua
Runtime: 78 ms
"""
class Solution(object):
    def insert(self, intervals, newInterval):
        
        index = len(intervals)
        for i in range(len(intervals)):
            if newInterval.start &lt; intervals[i].start:
                index = i
                break
        
        intervals.insert(index, newInterval)
        
        ans = []
        for interval in intervals:
            if not ans or interval.start &gt; ans[-1].end:
                ans.append(interval)
            else:
                ans[-1].end = max(ans[-1].end, interval.end)
        return ans</pre><p>&nbsp;</p>
<p>Solution 2:</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 13 ms
class Solution {
public:
    vector&lt;Interval&gt; insert(vector&lt;Interval&gt;&amp; intervals, Interval newInterval) {
        vector&lt;Interval&gt; l;
        vector&lt;Interval&gt; r;
        int start = newInterval.start;
        int end = newInterval.end;
        for (const Interval&amp; interval : intervals) {
            if (interval.end &lt; start)
                l.push_back(interval);
            else if (interval.start &gt; end)
                r.push_back(interval);
            else {
                start = min(start, interval.start);
                end = max(end, interval.end);
            }                
        }
        
        vector&lt;Interval&gt; ans(std::move(l));
        ans.emplace_back(start, end);
        ans.insert(ans.end(), r.begin(), r.end());
        return ans;
    }
};</pre><p>&nbsp;</p>
<p>Python</p><pre class="crayon-plain-tag">"""
Author: Huahua
Runtime: 68 ms
"""
class Solution(object):
    def insert(self, intervals, newInterval):
        start, end = newInterval.start, newInterval.end
        l, r = [], []        
        for interval in intervals:
            if interval.end &lt; start: l += interval, 
            elif interval.start &gt; end: r += interval,
            else: 
                start = min(start, interval.start)
                end = max(end, interval.end)
        return l + [Interval(start, end)] + r</pre><p>&nbsp;</p>
<p><strong>Related problems:</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/geometry/leetcode-56-merge-intervals/">[解题报告] LeetCode 56. Merge Intervals</a></li>
<li><a href="http://zxi.mytechroad.com/blog/tree/leetcode-218-the-skyline-problem/">[解题报告] LeetCode 218. The Skyline Problem</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/geometry/leetcode-57-insert-interval/">花花酱 LeetCode 57. Insert Interval</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/geometry/leetcode-57-insert-interval/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 56. Merge Intervals</title>
		<link>https://zxi.mytechroad.com/blog/geometry/leetcode-56-merge-intervals/</link>
					<comments>https://zxi.mytechroad.com/blog/geometry/leetcode-56-merge-intervals/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 15 Oct 2017 03:13:20 +0000</pubDate>
				<category><![CDATA[Geometry]]></category>
		<category><![CDATA[interval]]></category>
		<category><![CDATA[merge]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[sweep line]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=578</guid>

					<description><![CDATA[<p>Problem: Given a collection of intervals, merge all overlapping intervals. For example, Given [1,3],[2,6],[8,10],[15,18], return [1,6],[8,10],[15,18]. Idea: Sweep line Solution: C++ [crayon-663c64836b710965030148/] Python [crayon-663c64836b712227841382/] &#160; Related Problems:&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/geometry/leetcode-56-merge-intervals/">花花酱 LeetCode 56. Merge Intervals</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/6tLHjei-f0I?feature=oembed" frameborder="0" gesture="media" allowfullscreen></iframe></p>
<p><strong>Problem:</strong></p>
<p>Given a collection of intervals, merge all overlapping intervals.</p>
<p>For example,<br />
Given <code>[1,3],[2,6],[8,10],[15,18]</code>,<br />
return <code>[1,6],[8,10],[15,18]</code>.</p>
<p><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><br />
<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><br />
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<p><strong>Idea:</strong></p>
<p>Sweep line</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/56-ep85-1.png"><img class="alignnone size-full wp-image-584" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/56-ep85-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/56-ep85-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/56-ep85-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/56-ep85-1-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/56-ep85-1-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p><strong>Solution: </strong></p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 12 ms
class Solution {
public:
    vector&lt;Interval&gt; merge(vector&lt;Interval&gt;&amp; intervals) {
        if (intervals.empty()) return {};
        
        std::sort(intervals.begin(), intervals.end(), 
                  [](const Interval&amp; a, const Interval&amp; b){
                        return a.start &lt; b.start;
                    });
        
        vector&lt;Interval&gt; ans;        
        for (const auto&amp; interval : intervals) {
            if (ans.empty() || interval.start &gt; ans.back().end) {
                ans.push_back(interval);
            } else {
                ans.back().end = max(ans.back().end, interval.end);
            }
        }
        
        return ans;
    }
};</pre><p>Python</p><pre class="crayon-plain-tag">"""
Author: Huahua
Runtime: 69 ms
"""
class Solution(object):
    def merge(self, intervals):
        ans = []
        for interval in sorted(intervals, key=lambda x: x.start):
            if not ans or interval.start &gt; ans[-1].end:
                ans.append(interval)
            else:
                ans[-1].end = max(ans[-1].end, interval.end)
        return ans</pre><p>&nbsp;</p>
<p><strong>Related Problems:</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/geometry/leetcode-57-insert-interval/">[解题报告] LeetCode 57. Insert Interval</a></li>
<li><a href="http://zxi.mytechroad.com/blog/tree/leetcode-218-the-skyline-problem/">[解题报告] LeetCode 218. The Skyline Problem</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/geometry/leetcode-56-merge-intervals/">花花酱 LeetCode 56. Merge Intervals</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/geometry/leetcode-56-merge-intervals/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 21: Merge Two Sorted Lists</title>
		<link>https://zxi.mytechroad.com/blog/leetcode/leetcode-21-merge-two-sorted-lists/</link>
					<comments>https://zxi.mytechroad.com/blog/leetcode/leetcode-21-merge-two-sorted-lists/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 03 Sep 2017 18:00:03 +0000</pubDate>
				<category><![CDATA[Leetcode]]></category>
		<category><![CDATA[List]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[merge]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[sorted]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=57</guid>

					<description><![CDATA[<p>Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/leetcode/leetcode-21-merge-two-sorted-lists/">花花酱 LeetCode 21: Merge Two Sorted Lists</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/qckKEYP9bBA?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p>Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.</p>
<p><strong>Solution 1</strong>: Iterative O(n)</p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
    Solution 1: Iterative
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode dummy(0);
        ListNode* tail=&amp;dummy;
        while(l1 &amp;&amp; l2) {
            if(l1-&gt;val &lt; l2-&gt;val) {
                tail-&gt;next=l1;
                l1=l1-&gt;next;
            }else{
                tail-&gt;next=l2;
                l2=l2-&gt;next;
            }
            tail=tail-&gt;next;
        }
        
        if(l1) tail-&gt;next = l1;
        if(l2) tail-&gt;next = l2;
        
        return dummy.next;
        
    }
};</pre><p>&nbsp;</p>
<p><strong>Solution 2</strong>: Recursive O(n)</p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        // If one of the list is emptry, return the other one.
        if(!l1 || !l2) return l1 ? l1 : l2;
        // The smaller one becomes the head.
        if(l1-&gt;val &lt; l2-&gt;val) {
            l1-&gt;next = mergeTwoLists(l1-&gt;next, l2);
            return l1;
        } else {
            l2-&gt;next = mergeTwoLists(l1, l2-&gt;next);
            return l2;
        }
    }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/leetcode/leetcode-21-merge-two-sorted-lists/">花花酱 LeetCode 21: Merge Two Sorted Lists</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/leetcode/leetcode-21-merge-two-sorted-lists/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
