<?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>in place Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/in-place/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/in-place/</link>
	<description></description>
	<lastBuildDate>Thu, 09 Jul 2020 00:24:49 +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>in place Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/in-place/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 1502. Can Make Arithmetic Progression From Sequence</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1502-can-make-arithmetic-progression-from-sequence/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1502-can-make-arithmetic-progression-from-sequence/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 05 Jul 2020 15:29:08 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[in place]]></category>
		<category><![CDATA[swap]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7025</guid>

					<description><![CDATA[<p>Given an array of numbers&#160;arr.&#160;A sequence of numbers is called an arithmetic progression&#160;if the difference between any two consecutive elements is the same. Return&#160;true&#160;if the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1502-can-make-arithmetic-progression-from-sequence/">花花酱 LeetCode 1502. Can Make Arithmetic Progression From Sequence</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given an array of numbers&nbsp;<code>arr</code>.&nbsp;A sequence of numbers is called an arithmetic progression&nbsp;if the difference between any two consecutive elements is the same.</p>



<p>Return&nbsp;<code>true</code>&nbsp;if the array can be rearranged to form an arithmetic progression, otherwise, return&nbsp;<code>false</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [3,5,1]
<strong>Output:</strong> true
<strong>Explanation: </strong>We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [1,2,4]
<strong>Output:</strong> false
<strong>Explanation: </strong>There is no way to reorder the elements to obtain an arithmetic progression.
</pre>



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



<ul><li><code>2 &lt;= arr.length &lt;= 1000</code></li><li><code>-10^6 &lt;= arr[i] &lt;= 10^6</code></li></ul>



<h2><strong>Solution 1: Sort and check.</strong></h2>



<p>Time complexity: O(nlog)<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 canMakeArithmeticProgression(vector&lt;int&gt;&amp; arr) {
    sort(begin(arr), end(arr));
    const int diff = arr[1] - arr[0];
    for (int i = 2; i &lt; arr.size(); ++i)
      if (arr[i] - arr[i - 1] != diff) return false;
    return true;
  }
};</pre>

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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
  public boolean canMakeArithmeticProgression(int[] arr) {
    Arrays.sort(arr);
    int diff = arr[1] - arr[0];
    for (int i = 2; i &lt; arr.length; ++i)
      if (arr[i] - arr[i - 1] != diff) return false;
    return true;
  }
}</pre>

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

<pre class="crayon-plain-tag">class Solution:
  def canMakeArithmeticProgression(self, arr: List[int]) -&gt; bool:
    arr.sort()
    diff = arr[1] - arr[0]
    return all(i - j == diff for i, j in zip(arr[1:], arr[:-1]))</pre>
</div></div>



<h2><strong>Solution 2: Rearrange the array</strong></h2>



<p>Find min / max / diff and put each element into its correct position by swapping elements in place.</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:
  bool canMakeArithmeticProgression(vector&lt;int&gt;&amp; arr) {
    const int n = arr.size();
    const auto [loit, hiit] = minmax_element(cbegin(arr), cend(arr));
    const auto [lo, hi] = pair{*loit, *hiit};
    if ((hi - lo) % (n - 1)) return false;
    const int diff = (hi - lo) / (n - 1);
    if (diff == 0) return true;
    for (int i = 0; i &lt; n; ++i) {
      if ((arr[i] - lo) % diff) return false;
      const int idx = (arr[i] - lo) / diff;
      if (idx != i) swap(arr[i--], arr[idx]);
    }
    return true;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1502-can-make-arithmetic-progression-from-sequence/">花花酱 LeetCode 1502. Can Make Arithmetic Progression From Sequence</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1502-can-make-arithmetic-progression-from-sequence/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 48. Rotate Image</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-48-rotate-image/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-48-rotate-image/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 02 Oct 2019 16:20:55 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[flip]]></category>
		<category><![CDATA[in place]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[mirror]]></category>
		<category><![CDATA[O(n^2)]]></category>
		<category><![CDATA[rotate]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5698</guid>

					<description><![CDATA[<p>You are given an&#160;n&#160;x&#160;n&#160;2D matrix representing an image. Rotate the image by 90 degrees (clockwise). Note: You have to rotate the image&#160;in-place, which means you&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-48-rotate-image/">花花酱 LeetCode 48. Rotate Image</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 an&nbsp;<em>n</em>&nbsp;x&nbsp;<em>n</em>&nbsp;2D matrix representing an image.</p>



<p>Rotate the image by 90 degrees (clockwise).</p>



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



<p>You have to rotate the image&nbsp;<a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank" rel="noreferrer noopener"><strong>in-place</strong></a>, which means you have to modify the input 2D matrix directly.&nbsp;<strong>DO NOT</strong>&nbsp;allocate another 2D matrix and do the rotation.</p>



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



<pre class="wp-block-preformatted;crayon:false">Given <strong>input matrix</strong> = 
[
  [1,2,3],
  [4,5,6],
  [7,8,9]
],

rotate the input matrix <strong>in-place</strong> such that it becomes:
[
  [7,4,1],
  [8,5,2],
  [9,6,3]
]
</pre>



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



<pre class="wp-block-preformatted;crayon:false">Given <strong>input matrix</strong> =
[
  [ 5, 1, 9,11],
  [ 2, 4, 8,10],
  [13, 3, 6, 7],
  [15,14,12,16]
], 

rotate the input matrix <strong>in-place</strong> such that it becomes:
[
  [15,13, 2, 5],
  [14, 3, 4, 1],
  [12, 6, 8, 9],
  [16, 7,10,11]
]</pre>



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



<p>First pass: mirror around diagonal <br>Second pass: mirror around y axis</p>



<p>Time complexity: O(n^2)<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 rotate(vector&lt;vector&lt;int&gt;&gt;&amp; matrix) {
    const int n = matrix.size();
    for (int i = 0; i &lt; n; ++i)
      for (int j = i + 1; j &lt; n; ++j)
        swap(matrix[i][j], matrix[j][i]);
    for (int i = 0; i &lt; n; ++i)
      reverse(begin(matrix[i]), end(matrix[i]));
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-48-rotate-image/">花花酱 LeetCode 48. Rotate Image</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-48-rotate-image/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 73. Set Matrix Zeroes</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-73-set-matrix-zeroes/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-73-set-matrix-zeroes/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 09 Feb 2019 19:32:10 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[constant space]]></category>
		<category><![CDATA[in place]]></category>
		<category><![CDATA[O(1)]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4806</guid>

					<description><![CDATA[<p>Given a&#160;m&#160;x&#160;n&#160;matrix, if an element is 0, set its entire row and column to 0. Do it&#160;in-place. Example 1: Input: [ &#160; [1,1,1], &#160; [1,0,1],&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-73-set-matrix-zeroes/">花花酱 LeetCode 73. Set Matrix Zeroes</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given a&nbsp;<em>m</em>&nbsp;x&nbsp;<em>n</em>&nbsp;matrix, if an element is 0, set its entire row and column to 0. Do it&nbsp;<a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank" rel="noreferrer noopener"><strong>in-place</strong></a>.</p>



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



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



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



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



<p><strong>Follow up:</strong></p>



<ul><li>A straight forward solution using O(<em>m</em><em>n</em>) space is probably a bad idea.</li><li>A simple improvement uses O(<em>m</em>&nbsp;+&nbsp;<em>n</em>) space, but still not the best solution.</li><li>Could you devise a constant space solution?</li></ul>



<h2><strong>Solution 1</strong></h2>



<p>Use two arrays to track whether the i-th row / j-th column need to be zeroed.</p>



<p>Time complexity: O(mn)<br>Space complexity: O(m+n)</p>



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

<pre class="crayon-plain-tag">class Solution {
public:
  void setZeroes(vector&lt;vector&lt;int&gt;&gt;&amp; matrix) {
    const int m = matrix.size();
    const int n = matrix[0].size();
    vector&lt;int&gt; rows(m);
    vector&lt;int&gt; cols(n);
    for (int i = 0; i &lt; m; ++i)
      for (int j = 0; j &lt; n; ++j) {
        rows[i] |= (matrix[i][j] == 0);
        cols[j] |= (matrix[i][j] == 0);
      }
    for (int i = 0; i &lt; m; ++i)
      for (int j = 0; j &lt; n; ++j)
        if (rows[i] || cols[j]) matrix[i][j] = 0;        
  }
};</pre>
</div></div>



<h2><strong>Solution 2</strong></h2>



<p>Use the first row / first col to indicate whether the i-th row / j-th column need be zeroed.</p>



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

<pre class="crayon-plain-tag">class Solution {
public:
  void setZeroes(vector&lt;vector&lt;int&gt;&gt;&amp; matrix) {
    const int m = matrix.size();
    const int n = matrix[0].size();
    
    bool col0 = false;
    bool row0 = false;
    
    for (int i = 0; i &lt; m; ++i) 
      col0 |= (matrix[i][0] == 0);
    for (int j = 0; j &lt; n; ++j) 
      row0 |= (matrix[0][j] == 0);
    
    for (int i = 1; i &lt; m; ++i)
      for (int j = 1; j &lt; n; ++j)
        if (matrix[i][j] == 0)
          matrix[0][j] = matrix[i][0] = 0;      
    
    for (int i = 1; i &lt; m; ++i)
      for (int j = 1; j &lt; n; ++j)
        if (matrix[i][0] == 0 || matrix[0][j] == 0)
          matrix[i][j] = 0;
    
    if (row0)
      for (int j = 0; j &lt; n; ++j) 
        matrix[0][j] = 0;
    
    if (col0)
      for (int i = 0; i &lt; m; ++i) 
        matrix[i][0] = 0;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-73-set-matrix-zeroes/">花花酱 LeetCode 73. Set Matrix Zeroes</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-73-set-matrix-zeroes/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 31. Next Permutation</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-31-next-permutation/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-31-next-permutation/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 03 Oct 2018 02:28:58 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[in place]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[permutation]]></category>
		<category><![CDATA[reverse]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4146</guid>

					<description><![CDATA[<p>Problem Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-31-next-permutation/">花花酱 LeetCode 31. Next Permutation</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>Implement <strong>next permutation</strong>, which rearranges numbers into the lexicographically next greater permutation of numbers.</p>
<p>If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).</p>
<p>The replacement must be <strong><a href="http://en.wikipedia.org/wiki/In-place_algorithm" target="_blank" rel="noopener">in-place</a></strong> and use only constant extra memory.</p>
<p>Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.</p>
<p><code>1,2,3</code> → <code>1,3,2</code><br />
<code>3,2,1</code> → <code>1,2,3</code><br />
<code>1,1,5</code> → <code>1,5,1</code></p>
<h1><strong>Solution</strong></h1>
<p>Find the last acceding element x, swap with the smallest number y, y is after x that and y is greater than x.</p>
<p>Reverse the elements after x.</p>
<p>Time complexity: O(n)</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, 8 ms
class Solution {
public:
  void nextPermutation(vector&lt;int&gt;&amp; nums) {
    int i = nums.size() - 2;
    while (i &gt;= 0 &amp;&amp; nums[i + 1] &lt;= nums[i]) --i;
    if (i &gt;= 0) {
      int j = nums.size() - 1;
      while (j &gt;= 0 &amp;&amp; nums[j] &lt;= nums[i]) --j;
      swap(nums[i], nums[j]);
    }
    reverse(begin(nums) + i + 1, end(nums));
  }
};</pre><p></div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag"># Author: Huahua, 48 ms
class Solution:
  def nextPermutation(self, nums):
    n = len(nums)
    i = n - 2
    while i &gt;= 0 and nums[i] &gt;= nums[i + 1]: i -= 1
    if i &gt;= 0:
      j = n - 1
      while j &gt;= 0 and nums[j] &lt;= nums[i]: j -= 1
      nums[i], nums[j] = nums[j], nums[i]
    nums[i + 1:] = nums[i+1:][::-1]</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-31-next-permutation/">花花酱 LeetCode 31. Next Permutation</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-31-next-permutation/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 27. Remove Element</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-27-remove-element/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-27-remove-element/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 02 Oct 2018 19:32:20 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[in place]]></category>
		<category><![CDATA[remove]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4135</guid>

					<description><![CDATA[<p>Problem Given an array nums and a value val, remove all instances of that value in-place and return the new length. Do not allocate extra space for another array, you&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-27-remove-element/">花花酱 LeetCode 27. Remove Element</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>Given an array <em>nums</em> and a value <em>val</em>, remove all instances of that value <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank" rel="noopener"><strong>in-place</strong></a> and return the new length.</p>
<p>Do not allocate extra space for another array, you must do this by <strong>modifying the input array <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank" rel="noopener">in-place</a></strong> with O(1) extra memory.</p>
<p>The order of elements can be changed. It doesn&#8217;t matter what you leave beyond the new length.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false">Given <em>nums</em> = <strong>[3,2,2,3]</strong>, <em>val</em> = <strong>3</strong>,

Your function should return length = <strong>2</strong>, with the first two elements of <em>nums</em> being <strong>2</strong>.

It doesn't matter what you leave beyond the returned length.
</pre>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false">Given <em>nums</em> = <strong>[0,1,2,2,3,0,4,2]</strong>, <em>val</em> = <strong>2</strong>,

Your function should return length = <strong><code>5</code></strong>, with the first five elements of <em><code>nums</code></em> containing <strong><code>0</code></strong>, <strong><code>1</code></strong>, <strong><code>3</code></strong>, <strong><code>0</code></strong>, and <strong>4</strong>. Note that the order of those five elements can be arbitrary. It doesn't matter what values are set beyond the returned length.</pre>
<p><strong>Clarification:</strong></p>
<p>Confused why the returned value is an integer but your answer is an array?</p>
<p>Note that the input array is passed in by <strong>reference</strong>, which means modification to the input array will be known to the caller as well.</p>
<p>Internally you can think of this:</p>
<pre class="crayon:false">// <strong>nums</strong> is passed in by reference. (i.e., without making a copy)
int len = removeElement(nums, val);

// any modification to <strong>nums</strong> in your function would be known by the caller.
// using the length returned by your function, it prints the first <strong>len</strong> elements.
for (int i = 0; i &lt; len; i++) {
    print(nums[i]);
}</pre>
<h1><strong>Solution:</strong></h1>
<p>Time complexity: O(n)</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:
  int removeElement(vector&lt;int&gt;&amp; nums, int val) {
    int len = 0;
    for (int num : nums)
      if (num != val) nums[len++] = num;
    return len;
  }
};</pre><p></div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">class Solution:
  def removeElement(self, nums, val):
    l = 0
    for num in nums:
      if num != val:
        nums[l], l = num, l + 1        
    return l</pre><p></div></div></p>
<h1><strong>Related Problems</strong></h1>
<ul>
<li><a href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-26-remove-duplicates-from-sorted-array/">花花酱 LeetCode 26. Remove Duplicates from Sorted Array</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-27-remove-element/">花花酱 LeetCode 27. Remove Element</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-27-remove-element/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 289. Game of Life</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-289-game-of-life/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-289-game-of-life/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 28 Jun 2018 05:26:01 +0000</pubDate>
				<category><![CDATA[Bit]]></category>
		<category><![CDATA[Simulation]]></category>
		<category><![CDATA[bit]]></category>
		<category><![CDATA[in place]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2944</guid>

					<description><![CDATA[<p>Problem According to the Wikipedia&#8217;s article: &#8220;The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-289-game-of-life/">花花酱 LeetCode 289. Game of Life</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/juGxbF-eadU?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<h1><strong>Problem</strong></h1>
<p>According to the <a href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" target="_blank" rel="noopener">Wikipedia&#8217;s article</a>: &#8220;The <b>Game of Life</b>, also known simply as <b>Life</b>, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.&#8221;</p>
<p>Given a <i>board</i> with <i>m</i> by <i>n</i> cells, each cell has an initial state <i>live</i> (1) or <i>dead</i> (0). Each cell interacts with its <a href="https://en.wikipedia.org/wiki/Moore_neighborhood" target="_blank" rel="noopener">eight neighbors</a> (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):</p>
<ol>
<li>Any live cell with fewer than two live neighbors dies, as if caused by under-population.</li>
<li>Any live cell with two or three live neighbors lives on to the next generation.</li>
<li>Any live cell with more than three live neighbors dies, as if by over-population..</li>
<li>Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.</li>
</ol>
<p>Write a function to compute the next state (after one update) of the board given its current state. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously.</p>
<p><strong>Example:</strong></p>
<pre class="crayon:false"><strong>Input: 
</strong><span id="example-input-1-1">[
  [0,1,0],
  [0,0,1],
  [1,1,1],
  [0,0,0]
]</span>
<strong>Output: 
</strong><span id="example-output-1">[
  [0,0,0],
  [1,0,1],
  [0,1,1],
  [0,1,0]
]</span>
</pre>
<p><b>Follow up</b>:</p>
<ol>
<li>Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells.</li>
<li>In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems?</li>
</ol>
<h1><img class="alignnone size-full wp-image-2947" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/06/289-ep199.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/06/289-ep199.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/06/289-ep199-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/06/289-ep199-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></h1>
<h1><strong>Solution: Simulation</strong></h1>
<p>Time complexity: O(mn)</p>
<p>Space complexity: O(1)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 5 ms
class Solution {
public:
  void gameOfLife(vector&lt;vector&lt;int&gt;&gt;&amp; board) {
    int m = board.size();
    int n = m ? board[0].size() : 0;
    for (int i = 0; i &lt; m; ++i)
      for (int j = 0; j &lt; n; ++j) {
        int lives = 0;
        // Scan the 3x3 region including (j, i).
        for (int y = max(0, i - 1); y &lt; min(m, i + 2); ++y)
          for (int x = max(0, j - 1); x &lt; min(n, j + 2); ++x)
            lives += board[y][x] &amp; 1;
        if (lives == 3 || lives - board[i][j] == 3) board[i][j] |= 0b10;
      }
    for (int i = 0; i &lt; m; ++i)
      for (int j = 0; j &lt; n; ++j) 
        board[i][j] &gt;&gt;= 1;
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-289-game-of-life/">花花酱 LeetCode 289. Game of Life</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-289-game-of-life/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 443. String Compression</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-443-string-compression/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-443-string-compression/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 24 Mar 2018 19:50:55 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[compression]]></category>
		<category><![CDATA[encoding]]></category>
		<category><![CDATA[in place]]></category>
		<category><![CDATA[run length]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2354</guid>

					<description><![CDATA[<p>Problem 题目大意：对一个string进行in-place的run length encoding。 https://leetcode.com/problems/string-compression/description/ Given an array of characters, compress it in-place. The length after compression must always be smaller than or equal to the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-443-string-compression/">花花酱 LeetCode 443. String Compression</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>题目大意：对一个string进行in-place的run length encoding。</p>
<p><a href="https://leetcode.com/problems/string-compression/description/">https://leetcode.com/problems/string-compression/description/</a></p>
<p>Given an array of characters, compress it <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank" rel="noopener"><b>in-place</b></a>.</p>
<p>The length after compression must always be smaller than or equal to the original array.</p>
<p>Every element of the array should be a <b>character</b> (not int) of length 1.</p>
<p>After you are done <b>modifying the input array <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank" rel="noopener">in-place</a></b>, return the new length of the array.</p>
<p><b>Follow up:</b><br />
Could you solve it using only O(1) extra space?</p>
<p><b>Example 1:</b></p>
<pre class="crayon:false"><b>Input:</b>
["a","a","b","b","c","c","c"]

<b>Output:</b>
Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]

<b>Explanation:</b>
"aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3".
</pre>
<p><b>Example 2:</b></p>
<pre class="crayon:false"><b>Input:</b>
["a"]

<b>Output:</b>
Return 1, and the first 1 characters of the input array should be: ["a"]

<b>Explanation:</b>
Nothing is replaced.
</pre>
<p><b>Example 3:</b></p>
<pre class="crayon:false  "><b>Input:</b>
["a","b","b","b","b","b","b","b","b","b","b","b","b"]

<b>Output:</b>
Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].

<b>Explanation:</b>
Since the character "a" does not repeat, it is not compressed. "bbbbbbbbbbbb" is replaced by "b12".
Notice each digit has it's own entry in the array.
</pre>
<p><b>Note:</b></p>
<ol>
<li>All characters have an ASCII value in <code>[35, 126]</code>.</li>
<li><code>1 &lt;= len(chars) &lt;= 1000</code>.</li>
</ol>
<h1><strong>Solution</strong></h1>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(1)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 9 ms
class Solution {
public:
  int compress(vector&lt;char&gt;&amp; chars) {
    const int n = chars.size();
    int p = 0;
    for (int i = 1; i &lt;= n; ++i) {
      int count = 1;
      while (i &lt; n &amp;&amp; chars[i] == chars[i - 1]) { ++i; ++count; }
      chars[p++] = chars[i - 1];
      if (count == 1) continue;
      for (char c : to_string(count))
        chars[p++] = c;
    }
    return p;
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-443-string-compression/">花花酱 LeetCode 443. String Compression</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-443-string-compression/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
