<?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>Easy Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/category/difficulty/easy/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/category/difficulty/easy/</link>
	<description></description>
	<lastBuildDate>Mon, 30 Sep 2019 04:42:08 +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>Easy Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/category/difficulty/easy/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 783. Minimum Distance Between BST Nodes</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-783-minimum-distance-between-bst-nodes/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-783-minimum-distance-between-bst-nodes/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 11 Feb 2018 06:01:13 +0000</pubDate>
				<category><![CDATA[Easy]]></category>
		<category><![CDATA[Tree]]></category>
		<category><![CDATA[BST]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1796</guid>

					<description><![CDATA[<p>Given a Binary Search Tree (BST) with the root node root, return the minimum difference between the values of any two different nodes in the tree. Example&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-783-minimum-distance-between-bst-nodes/">花花酱 LeetCode 783. Minimum Distance Between BST Nodes</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<div class="question-description">
<div>
<p>Given a Binary Search Tree (BST) with the root node <code>root</code>, return the minimum difference between the values of any two different nodes in the tree.</p>
<p><strong>Example :</strong></p><pre class="crayon-plain-tag">Input: root = [4,2,6,1,3,null,null]
Output: 1
Explanation:
Note that root is a TreeNode object, not an array.

The given tree [4,2,6,1,3,null,null] is represented by the following diagram:

          4
        /   \
      2      6
     / \    
    1   3  

while the minimum difference in this tree is 1, it occurs between node 1 and node 2, also between node 3 and node 2.</pre><p><strong>Note:</strong></p>
<ol>
<li>The size of the BST will be between 2 and <code>100</code>.</li>
<li>The BST is always valid, each node&#8217;s value is an integer, and each node&#8217;s value is different.</li>
</ol>
</div>
</div>
<p><b>Solution 1: In order traversal </b></p>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(n)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 783
class Solution {
public:
  int minDiffInBST(TreeNode* root) {
    min_diff_ = INT_MAX;
    prev_ = nullptr;
    minDiff(root);
    return min_diff_;
  }
private:
  int min_diff_;
  int* prev_;
  void minDiff(TreeNode* root) {
    if (root == nullptr) return;    
    minDiff(root-&gt;left);
    if (prev_ != nullptr)
      min_diff_ = min(min_diff_, abs(root-&gt;val - *prev_));
    prev_ = &amp;root-&gt;val;
    minDiff(root-&gt;right);
  }
};</pre><p><strong>Related Problems:</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/tree/leetcode-530-minimum-absolute-difference-in-bst/">花花酱 LeetCode 530. Minimum Absolute Difference in BST</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-783-minimum-distance-between-bst-nodes/">花花酱 LeetCode 783. Minimum Distance Between BST Nodes</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-783-minimum-distance-between-bst-nodes/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode  766. Toeplitz Matrix</title>
		<link>https://zxi.mytechroad.com/blog/difficulty/easy/leetcode-766-toeplitz-matrix/</link>
					<comments>https://zxi.mytechroad.com/blog/difficulty/easy/leetcode-766-toeplitz-matrix/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 03 Feb 2018 04:41:59 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[Easy]]></category>
		<category><![CDATA[matrix]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1732</guid>

					<description><![CDATA[<p>A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element. Now given an M x N matrix, return True if and only if the matrix is Toeplitz.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/difficulty/easy/leetcode-766-toeplitz-matrix/">花花酱 LeetCode  766. Toeplitz Matrix</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>A matrix is <em>Toeplitz</em> if every diagonal from top-left to bottom-right has the same element.</p>
<p>Now given an <code>M x N</code> matrix, return <code>True</code> if and only if the matrix is <em>Toeplitz</em>.<br />
<strong>Example 1:</strong></p><pre class="crayon-plain-tag">Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
Output: True
Explanation:
1234
5123
9512

In the above grid, the&nbsp;diagonals are &quot;[9]&quot;, &quot;[5, 5]&quot;, &quot;[1, 1, 1]&quot;, &quot;[2, 2, 2]&quot;, &quot;[3, 3]&quot;, &quot;[4]&quot;, and in each diagonal all elements are the same, so the answer is True.</pre><p><strong>Example 2:</strong></p><pre class="crayon-plain-tag">Input: matrix = [[1,2],[2,2]]
Output: False
Explanation:
The diagonal &quot;[1, 2]&quot; has different elements.</pre><p><strong>Note:</strong></p>
<ol>
<li><code>matrix</code> will be a 2D array of integers.</li>
<li><code>matrix</code> will have a number of rows and columns in range <code>[1, 20]</code>.</li>
<li><code>matrix[i][j]</code> will be integers in range <code>[0, 99]</code>.</li>
</ol>
<p><strong>Idea:</strong></p>
<p>Check m[i][j] with m[i-1][j-1]</p>
<p><strong>Solution: Brute Force</strong></p>
<p>Time complexity: O(n*m)</p>
<p>Space complexity: O(1)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 32 ms
class Solution {
public:
  bool isToeplitzMatrix(vector&lt;vector&lt;int&gt;&gt;&amp; matrix) {
    for (int i = 1; i &lt; matrix.size(); ++i)
      for (int j = 1; j &lt; matrix[0].size(); ++j)
        if (matrix[i][j] != matrix[i - 1][j - 1]) return false;
    return true;
  }
};</pre><p>Java</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 29 ms
class Solution {
  public boolean isToeplitzMatrix(int[][] matrix) {
    for (int i = 1; i &lt; matrix.length; ++i)
      for (int j = 1; j &lt; matrix[0].length; ++j)
        if (matrix[i][j] != matrix[i - 1][j - 1]) return false;
    return true;
  }
}</pre><p>Python3</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 99 ms
"""
class Solution:
  def isToeplitzMatrix(self, matrix):
    m = len(matrix)
    n = len(matrix[0])
    for i in range(1, m):
      for j in range(1, n):
        if matrix[i][j] != matrix[i - 1][j - 1]: return False
    return True</pre><p>&nbsp;</p>
<p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/difficulty/easy/leetcode-766-toeplitz-matrix/">花花酱 LeetCode  766. Toeplitz Matrix</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/difficulty/easy/leetcode-766-toeplitz-matrix/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 762. Prime Number of Set Bits in Binary Representation</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-762-prime-number-of-set-bits-in-binary-representation/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-762-prime-number-of-set-bits-in-binary-representation/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 18 Jan 2018 06:08:40 +0000</pubDate>
				<category><![CDATA[Bit]]></category>
		<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[Easy]]></category>
		<category><![CDATA[bit]]></category>
		<category><![CDATA[prime]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1636</guid>

					<description><![CDATA[<p>题目大意：求给定范围内，数的二进制形式中1的个数为素数个的数字的个数。 Given two integers L and R, find the count of numbers in the range [L, R] (inclusive) having a prime number of set bits in their binary representation. (Recall&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-762-prime-number-of-set-bits-in-binary-representation/">花花酱 LeetCode 762. Prime Number of Set Bits in Binary Representation</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/KVKeyehcUuU?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p>题目大意：求给定范围内，数的二进制形式中1的个数为素数个的数字的个数。</p>
<p>Given two integers <code>L</code> and <code>R</code>, find the count of numbers in the range <code>[L, R]</code> (inclusive) having a prime number of set bits in their binary representation.</p>
<p>(Recall that the number of set bits an integer has is the number of <code>1</code>s present when written in binary. For example, <code>21</code> written in binary is <code>10101</code> which has 3 set bits. Also, 1 is not a prime.)</p>
<p><b>Example 1:</b></p><pre class="crayon-plain-tag">Input: L = 6, R = 10
Output: 4
Explanation:
6 -&gt; 110 (2 set bits, 2 is prime)
7 -&gt; 111 (3 set bits, 3 is prime)
9 -&gt; 1001 (2 set bits , 2 is prime)
10-&gt;1010 (2 set bits , 2 is prime)</pre><p><b>Example 2:</b></p><pre class="crayon-plain-tag">Input: L = 10, R = 15
Output: 5
Explanation:
10 -&gt; 1010 (2 set bits, 2 is prime)
11 -&gt; 1011 (3 set bits, 3 is prime)
12 -&gt; 1100 (2 set bits, 2 is prime)
13 -&gt; 1101 (3 set bits, 3 is prime)
14 -&gt; 1110 (3 set bits, 3 is prime)
15 -&gt; 1111 (4 set bits, 4 is not prime)</pre><p><b>Note:</b></p>
<ol>
<li><code>L, R</code> will be integers <code>L &lt;= R</code> in the range <code>[1, 10^6]</code>.</li>
<li><code>R - L</code> will be at most 10000.</li>
</ol>
<p><strong>Solution 1: Brute Force</strong></p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 22 ms
class Solution {
public:
  int countPrimeSetBits(int L, int R) {
    int ans = 0;
    for (int n = L; n &lt;= R; ++n)
      if (isPrime(bits(n))) ++ans;
    return ans;
  }
private:
  bool isPrime(int n) {
    if (n &lt;= 1) return false;
    if (n == 2) return true;      
    for (int i = 2; i &lt;= sqrt(n); ++i)
      if (n % i == 0) return false;
    return true;
  }
  
  int bits(int n) {
    int s = 0;
    while (n) {
      s += n &amp; 1;
      n &gt;&gt;= 1;
    }        
    return s;
  }
};</pre><p></p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 16 ms
class Solution {
public:
  int countPrimeSetBits(int L, int R) {
    int ans = 0;
    set&lt;int&gt; primes{2, 3, 5, 7, 11, 13, 17, 19};
    for (int n = L; n &lt;= R; ++n)
      if (primes.count(__builtin_popcountll(n))) ++ans;
    return ans;
  }
};</pre><p>&nbsp;</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 30 ms
class Solution {
public:
  int countPrimeSetBits(int L, int R) {
    int ans = 0;
    unordered_set&lt;int&gt; primes{2, 3, 5, 7, 11, 13, 17, 19};
    for (int n = L; n &lt;= R; ++n)
      if (primes.count(__builtin_popcountll(n))) ++ans;
    return ans;
  }
};</pre><p></p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 9 ms
class Solution {
public:
  int countPrimeSetBits(int L, int R) {
    int ans = 0;
    vector&lt;int&gt; p(20, 0);
    p[2] = p[3] = p[5] = p[7] = p[11] = p[13] = p[17] = p[19] = 1;
    for (int n = L; n &lt;= R; ++n)
      if (p[__builtin_popcountll(n)]) ++ans;
    return ans;
  }
};</pre><p></p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 8 ms
class Solution {
public:
  int countPrimeSetBits(int L, int R) {
    constexpr int magic = 665772;
    int ans = 0;
    for (int n = L; n &lt;= R; ++n)
      if (magic &amp; (1 &lt;&lt; __builtin_popcountll(n))) ++ans;
    return ans;
  }
};</pre><p>&nbsp;</p>
<p>Java</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 39 ms
class Solution {
  public int countPrimeSetBits(int L, int R) {
    int ans = 0;
    for (int n = L; n &lt;= R; ++n)
      if (isPrime(bits(n))) ++ans;
    return ans;
  }
  
  private boolean isPrime(int n) {
    if (n &lt;= 1) return false;
    if (n == 2) return true;      
    for (int i = 2; i &lt;= (int)Math.sqrt(n); ++i)
      if (n % i == 0) return false;
    return true;
  }
  
  private int bits(int n) {
    int s = 0;
    while (n != 0) {
      s += n &amp; 1;
      n &gt;&gt;= 1;
    }        
    return s;
  }
}</pre><p>Python2</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 1618 ms
"""
class Solution(object):
  def countPrimeSetBits(self, L, R):
    def isPrime(n):
      if n &lt;= 1: return False
      if n == 2: return True
      for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0: return False
      return True

    def bits(n):
      s = 0
      while n != 0:
        s += n &amp; 1
        n &gt;&gt;= 1
      return s

    ans = 0
    for n in range(L, R + 1):
      if isPrime(bits(n)): ans += 1
    return ans</pre><p>Python2</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 1163 ms
"""
class Solution(object):
  def countPrimeSetBits(self, L, R):
    def bits(n):
      s = 0
      while n != 0:
        s += n &amp; 1
        n &gt;&gt;= 1
      return s
    
    primes = set([2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31])

    ans = 0
    for n in range(L, R + 1):
      if bits(n) in primes: ans += 1
    return ans</pre><p></p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 667 ms
"""
class Solution(object):   
  def countPrimeSetBits(self, L, R):
    def bits(n):
      s = 0
      while n != 0:
        n &amp;= n - 1;
        s += 1
      return s
        
    ans = 0
    while L &lt;= R:
      if (665772 &gt;&gt; bits(L)) &amp; 1 &gt; 0: ans += 1
      L += 1

    return ans</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-762-prime-number-of-set-bits-in-binary-representation/">花花酱 LeetCode 762. Prime Number of Set Bits in Binary Representation</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/dynamic-programming/leetcode-762-prime-number-of-set-bits-in-binary-representation/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode. 69 Sqrt(x)</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-69-sqrtx/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-69-sqrtx/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 17 Jan 2018 02:41:12 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[Easy]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[newton]]></category>
		<category><![CDATA[sqrt]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1613</guid>

					<description><![CDATA[<p>题目大意：让你实现开根号函数，只需要返回整数部分。 Problem: Implement int sqrt(int x). Compute and return the square root of x. x is guaranteed to be a non-negative integer. Example 1: [crayon-663cb600db231999832583/] Example 2: [crayon-663cb600db234304609230/]&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-69-sqrtx/">花花酱 LeetCode. 69 Sqrt(x)</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/_K4f9I11hYI?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p>题目大意：让你实现开根号函数，只需要返回整数部分。</p>
<p><strong>Problem:</strong></p>
<p>Implement <code>int sqrt(int x)</code>.</p>
<p>Compute and return the square root of <i>x</i>.</p>
<p><b>x</b> is guaranteed to be a non-negative integer.</p>
<p><b>Example 1:</b></p><pre class="crayon-plain-tag">Input: 4
Output: 2</pre><p><b>Example 2:</b></p><pre class="crayon-plain-tag">Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842...</pre><p>&nbsp;</p>
<p><img class="alignnone size-full wp-image-1624" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/69-ep158.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/69-ep158.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/69-ep158-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/69-ep158-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p><img class="alignnone size-full wp-image-1628" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/69-ep158-2-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/69-ep158-2-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/69-ep158-2-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/69-ep158-2-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p><ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-2404451723245401" data-ad-slot="7983117522"> </ins></p>
<h1><strong>Solution 1: Brute force</strong></h1>
<p>Time complexity: sqrt(x)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 40 ms
class Solution {
public:
  int mySqrt(int x) {
    if (x &lt;= 1) return x;
    for (long long s = 1; s &lt;= x; ++s)
      if (s * s &gt; x) return s - 1;
    return -1;
  }
};</pre><p></div><h2 class="tabtitle">C++ div</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 162 ms
class Solution {
public:
  int mySqrt(int x) {
    if (x &lt;= 1) return x;
    for (int s = 1; s &lt;= x; ++s)
      if (s &gt; x / s) return s - 1;
    return -1;
  }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 71 ms
class Solution {
  public int mySqrt(int x) {
    if (x &lt;= 1) return x;
    for (long s = 1; s &lt;= x; ++s)
      if (s * s &gt; x) return (int)s - 1;
    return -1;
  }
}</pre><p></div><h2 class="tabtitle">Python3 TLE</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">"""
Author: Huahua
TLE: 602 / 1017 test cases passed.
"""
class Solution:
  def mySqrt(self, x):
    if x &lt;= 1: return x
    s = 1
    while True:
      if s*s &gt; x: return s - 1
      s += 1
    return -1</pre><p></div></div></p>
<h1><strong>Solution 2: Binary search</strong></h1>
<p>Time 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: 12 ms
class Solution {
public:
  int mySqrt(int x) {      
    long l = 1;
    long r = static_cast&lt;long&gt;(x) + 1;
    while (l &lt; r) {
      long m = l + (r - l) / 2;
      if (m * m &gt; x) { 
        r = m;
      } else {
        l = m + 1;
      }
    }
    // l: smallest number such that l * l &gt; x
    return l - 1;
  }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 47 ms
class Solution {
  public int mySqrt(int x) {      
    int l = 1;
    int r = x;
    while (l &lt;= r) {
      int m = l + (r - l) / 2;
      if (m &gt; x / m) {
        r = m - 1;
      } else {
        l = m + 1;
      }
    }
    return r;
  }
}</pre><p></div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 119 ms
"""
class Solution:
  def mySqrt(self, a):
    l = 1
    r = a
    while l &lt;= r:
      m = l + (r - l) // 2
      if m * m &gt; a:
        r = m - 1
      else:
        l = m + 1
    return r;</pre><p></div></div></p>
<h1><strong>Solution 3: Newton&#8217;s method</strong></h1>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++ / float</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 28 ms
class Solution {
public:
    int mySqrt(int a) {
      constexpr double epsilon = 1e-2;
      double x = a;
      while (x * x - a &gt; epsilon) {
        x = (x + a / x) / 2.0;
      }
      return x;
    }
};</pre><p></div><h2 class="tabtitle">C++ / int</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 27 ms
class Solution {
public:
  int mySqrt(int a) {
    // f(x) = x^2 - a, find root of f(x)
    // Newton's method
    // f'(x) = 2x
    // x' = x - f(x) / f'(x) = x - (1/2*x - a/(2*x))
    //    = (x + a / x) / 2
    int x = a;
    while (x &gt; a / x)
      x = (x + a / x) / 2;
    return x;
  }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 44 ms
class Solution {
  public int mySqrt(int a) {    
    long x = a;
    while (x * x &gt; a)
      x = (x + a / x) / 2;    
    return (int)x;
  }
}</pre><p></div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 100 ms
"""
class Solution:
  def mySqrt(self, a):
    x = a
    while x * x &gt; a:
      x = (x + a // x) // 2
    return x</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-69-sqrtx/">花花酱 LeetCode. 69 Sqrt(x)</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/math/leetcode-69-sqrtx/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 758. Bold Words in String</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-758-bold-words-in-string/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-758-bold-words-in-string/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 09 Jan 2018 00:31:28 +0000</pubDate>
				<category><![CDATA[Easy]]></category>
		<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[String]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1565</guid>

					<description><![CDATA[<p>题目大意：给你一个字符串和一些要加粗的单词，返回加粗后的HTML代码。 Problem: Given a set of keywords words and a string S, make all appearances of all keywords in S bold. Any letters between &#60;b&#62; and &#60;/b&#62; tags become bold. The returned string should&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-758-bold-words-in-string/">花花酱 LeetCode 758. Bold Words in String</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/rUNE3VVcXAs?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p>题目大意：给你一个字符串和一些要加粗的单词，返回加粗后的HTML代码。</p>
<p><strong>Problem:</strong></p>
<p>Given a set of keywords <code>words</code> and a string <code>S</code>, make all appearances of all keywords in <code>S</code> bold. Any letters between <code>&lt;b&gt;</code> and <code>&lt;/b&gt;</code> tags become bold.</p>
<p>The returned string should use the least number of tags possible, and of course the tags should form a valid combination.</p>
<p>For example, given that <code>words = ["ab", "bc"]</code> and <code>S = "aabcd"</code>, we should return <code>"a&lt;b&gt;abc&lt;/b&gt;d"</code>. Note that returning <code>"a&lt;b&gt;a&lt;b&gt;b&lt;/b&gt;c&lt;/b&gt;d"</code> would use more tags, so it is incorrect.</p>
<p><b>Note:</b></p>
<ol>
<li><code>words</code> has length in range <code>[0, 50]</code>.</li>
<li><code>words[i]</code> has length in range <code>[1, 10]</code>.</li>
<li><code>S</code> has length in range <code>[0, 500]</code>.</li>
<li>All characters in <code>words[i]</code> and <code>S</code> are lowercase letters.</li>
</ol>
<p><img class="alignnone size-full wp-image-2520" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/758-ep155.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/758-ep155.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/758-ep155-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/758-ep155-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p><strong>Solution:</strong></p>
<p>C++</p>
<p>Time complexity: O(nL^2)</p>
<p>Space complexity: O(n + d)</p>
<p>d: size of dictionary</p>
<p>L: max length of the word which is 10.</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 13 ms
class Solution {
public:
    string boldWords(vector&lt;string&gt;&amp; words, string S) {
      const int kMaxWordLen = 10;      
      unordered_set&lt;string&gt; dict(words.begin(), words.end());
      
      int n = S.length();
      vector&lt;int&gt; bolded(n, 0);
      for (int i = 0; i &lt; n; ++i)
        for (int l = 1; l &lt;= min(n - i, kMaxWordLen); ++l)
          if (dict.count(S.substr(i, l)))
            std::fill(bolded.begin() + i, bolded.begin() + i + l, 1);
      
      string ans;
      for (int i = 0; i &lt; n; ++i) {
        if (bolded[i] &amp;&amp; (i == 0 || !bolded[i - 1])) ans += "&lt;b&gt;";
        ans += S[i];
        if (bolded[i] &amp;&amp; (i == n - 1 || !bolded[i + 1])) ans += "&lt;/b&gt;";
      }
      
      return ans;
    }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-758-bold-words-in-string/">花花酱 LeetCode 758. Bold Words in String</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-758-bold-words-in-string/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 760. Find Anagram Mappings</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-760-find-anagram-mappings/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-760-find-anagram-mappings/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 09 Jan 2018 00:17:16 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[Easy]]></category>
		<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[hashtable]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1563</guid>

					<description><![CDATA[<p>题目大意：输出数组A中每个元素在数组B中的索引。 Given two lists Aand B, and B is an anagram of A. B is an anagram of A means B is made by randomizing the order of the elements in A. We want to find an index&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-760-find-anagram-mappings/">花花酱 LeetCode 760. Find Anagram Mappings</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>题目大意：输出数组A中每个元素在数组B中的索引。</p>
<p>Given two lists <code>A</code>and <code>B</code>, and <code>B</code> is an anagram of <code>A</code>. <code>B</code> is an anagram of <code>A</code> means <code>B</code> is made by randomizing the order of the elements in <code>A</code>.</p>
<p>We want to find an <i>index mapping</i> <code>P</code>, from <code>A</code> to <code>B</code>. A mapping <code>P[i] = j</code> means the <code>i</code>th element in <code>A</code> appears in <code>B</code> at index <code>j</code>.</p>
<p>These lists <code>A</code> and <code>B</code> may contain duplicates. If there are multiple answers, output any of them.</p>
<p>For example, given</p><pre class="crayon-plain-tag">A = [12, 28, 46, 32, 50]
B = [50, 12, 32, 46, 28]</pre><p>We should return</p><pre class="crayon-plain-tag">[1, 4, 3, 2, 0]</pre><p>as <code>P[0] = 1</code> because the <code>0</code>th element of <code>A</code> appears at <code>B[1]</code>, and <code>P[1] = 4</code> because the <code>1</code>st element of <code>A</code>appears at <code>B[4]</code>, and so on.</p>
<p><strong>Solution:</strong></p>
<p>C++</p>
<p>Time complexity: O(nlogn)</p>
<p>Space complexity: O(n)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 6 ms
class Solution {
public:
    vector&lt;int&gt; anagramMappings(vector&lt;int&gt;&amp; A, vector&lt;int&gt;&amp; B) {
        map&lt;int, int&gt; indices;
        for (int i = 0; i &lt; B.size(); ++i)
            indices[B[i]] = i;
        vector&lt;int&gt; ans;
        for (const int a : A)
            ans.push_back(indices[a]);
        return ans;
    }
};</pre><p>C++ / No duplication</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 6 ms
class Solution {
public:
    vector&lt;int&gt; anagramMappings(vector&lt;int&gt;&amp; A, vector&lt;int&gt;&amp; B) {
        map&lt;int, vector&lt;int&gt;&gt; indices;
        for (int i = 0; i &lt; B.size(); ++i)
          indices[B[i]].push_back(i);
        vector&lt;int&gt; ans;
        for (const int a : A) {
          ans.push_back(indices[a].back());
          indices[a].pop_back();
        }
        return ans;
    }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-760-find-anagram-mappings/">花花酱 LeetCode 760. Find Anagram Mappings</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-760-find-anagram-mappings/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 476. Number Complement</title>
		<link>https://zxi.mytechroad.com/blog/difficulty/easy/476-number-complement/</link>
					<comments>https://zxi.mytechroad.com/blog/difficulty/easy/476-number-complement/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 30 Dec 2017 07:12:21 +0000</pubDate>
				<category><![CDATA[Bit]]></category>
		<category><![CDATA[Easy]]></category>
		<category><![CDATA[bit]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1366</guid>

					<description><![CDATA[<p>题目大意：给你一个正整数，输出和它互补的数（翻转所有的bits）。 Problem: Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation. Note: The given&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/difficulty/easy/476-number-complement/">花花酱 LeetCode 476. Number Complement</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/LZtFS4ple3c?feature=oembed" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen></iframe></p>
<p>题目大意：给你一个正整数，输出和它互补的数（翻转所有的bits）。</p>
<p><strong>Problem:</strong></p>
<p>Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.</p>
<p><b>Note:</b></p>
<ol>
<li>The given integer is guaranteed to fit within the range of a 32-bit signed integer.</li>
<li>You could assume no leading zero bit in the integer’s binary representation.</li>
</ol>
<p><b>Example 1:</b></p><pre class="crayon-plain-tag">Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.</pre><p><b>Example 2:</b></p><pre class="crayon-plain-tag">Input: 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.</pre><p><strong>Idea:</strong></p>
<p>Bit</p>
<p><script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><br />
<ins class="adsbygoogle" style="display:block" data-ad-format="fluid" data-ad-layout-key="-fb+5w+4e-db+86" data-ad-client="ca-pub-2404451723245401" data-ad-slot="2162692788"></ins><br />
<script><br />
     (adsbygoogle = window.adsbygoogle || []).push({});<br />
</script></p>
<p><strong>Solution:</strong></p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 3 ms
class Solution {
public:
    int findComplement(int num) {        
        int mask = ~0;        
        while (num &amp; mask) mask &lt;&lt;= 1;
        return ~num ^ mask;
    }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/difficulty/easy/476-number-complement/">花花酱 LeetCode 476. Number Complement</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/difficulty/easy/476-number-complement/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 367. Valid Perfect Square</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-367-valid-perfect-square/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-367-valid-perfect-square/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 30 Dec 2017 06:17:27 +0000</pubDate>
				<category><![CDATA[Easy]]></category>
		<category><![CDATA[Math]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1363</guid>

					<description><![CDATA[<p>题目大意：判断一个数是否是平方数。不能使用开根号函数。 Given a positive integer num, write a function which returns True if num is a perfect square else False. Note: Do not use any built-in library function such as sqrt.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-367-valid-perfect-square/">花花酱 LeetCode 367. Valid Perfect Square</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>题目大意：判断一个数是否是平方数。不能使用开根号函数。</p>
<p>Given a positive integer <i>num</i>, write a function which returns True if <i>num</i> is a perfect square else False.</p>
<p><b>Note:</b> <b>Do not</b> use any built-in library function such as <code>sqrt</code>.</p>
<p><b>Example 1:</b></p><pre class="crayon-plain-tag">Input: 16
Returns: True</pre><p><b>Example 2:</b></p><pre class="crayon-plain-tag">Input: 14
Returns: False</pre><p><strong>Idea:</strong></p>
<p>Binary search</p>
<p><strong>Solution:</strong></p>
<p>C++</p>
<p>Time complexity: O(log(num))</p>
<p>Space complexity: O(1)</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 0 ms
class Solution {
public:
    bool isPerfectSquare(int num) {        
        long l = 1;
        long r = num + 1;
        while (l &lt; r) {
            long m = l + (r - l) / 2;
            long t = m * m;
            if (t == num)
                return true;
            else if (t &gt; num)
                r = m;
            else
                l = m + 1;
        }
        
        return false;
    }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-367-valid-perfect-square/">花花酱 LeetCode 367. Valid Perfect Square</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/math/leetcode-367-valid-perfect-square/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 653. Two Sum IV &#8211; Input is a BST</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-653-two-sum-iv-input-is-a-bst/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-653-two-sum-iv-input-is-a-bst/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 30 Dec 2017 05:43:15 +0000</pubDate>
				<category><![CDATA[Easy]]></category>
		<category><![CDATA[Tree]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1360</guid>

					<description><![CDATA[<p>题目大意：给你一棵二叉搜索树，返回树中是否存在两个节点的和等于给定的目标值。 Problem: Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-653-two-sum-iv-input-is-a-bst/">花花酱 LeetCode 653. Two Sum IV &#8211; Input is a BST</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>题目大意：给你一棵二叉搜索树，返回树中是否存在两个节点的和等于给定的目标值。</p>
<p><strong>Problem:</strong></p>
<p>Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.</p>
<p><b>Example 1:</b></p><pre class="crayon-plain-tag">Input: 
    5
   / \
  3   6
 / \   \
2   4   7

Target = 9

Output: True</pre><p><b>Example 2:</b></p><pre class="crayon-plain-tag">Input: 
    5
   / \
  3   6
 / \   \
2   4   7

Target = 28

Output: False</pre><p></p>
<p><strong>Solution:</strong></p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 36 ms
class Solution {
public:
    bool findTarget(TreeNode* root, int k) {
        vector&lt;int&gt; nums;
        inorder(root, nums);
        int l = 0;
        int r = nums.size() - 1;
        while (l &lt; r) {
            int sum = nums[l] + nums[r];
            if (sum == k) return true;
            else if (sum &lt; k)
                ++l;
            else
                --r;
        }
        
        return false;
    }
private:
    void inorder(TreeNode* root, vector&lt;int&gt;&amp; nums) {
        if (root == nullptr) return;
        inorder(root-&gt;left, nums);
        nums.push_back(root-&gt;val);
        inorder(root-&gt;right, nums);
    }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-653-two-sum-iv-input-is-a-bst/">花花酱 LeetCode 653. Two Sum IV &#8211; Input is a BST</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-653-two-sum-iv-input-is-a-bst/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 748. Largest Number At Least Twice of Others</title>
		<link>https://zxi.mytechroad.com/blog/difficulty/easy/leetcode-748-largest-number-at-least-twice-of-others/</link>
					<comments>https://zxi.mytechroad.com/blog/difficulty/easy/leetcode-748-largest-number-at-least-twice-of-others/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 30 Dec 2017 05:24:30 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[Easy]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1357</guid>

					<description><![CDATA[<p>题目大意：给你一个数组，问你其中最大的数是不是比剩下的数大2倍以上，返回这样的数的索引。如果不存在，返回-1. Problem: In a given integer array nums, there is always exactly one largest element. Find whether the largest element in the array is at least&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/difficulty/easy/leetcode-748-largest-number-at-least-twice-of-others/">花花酱 LeetCode 748. Largest Number At Least Twice of Others</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>题目大意：给你一个数组，问你其中最大的数是不是比剩下的数大2倍以上，返回这样的数的索引。如果不存在，返回-1.</p>
<p><strong>Problem:</strong></p>
<p>In a given integer array <code>nums</code>, there is always exactly one largest element.</p>
<p>Find whether the largest element in the array is at least twice as much as every other number in the array.</p>
<p>If it is, return the <b>index</b> of the largest element, otherwise return -1.</p>
<p><b>Example 1:</b></p><pre class="crayon-plain-tag">Input: nums = [3, 6, 1, 0]
Output: 1
Explanation: 6 is the largest integer, and for every other number in the array x,
6 is more than twice as big as x.  The index of value 6 is 1, so we return 1.</pre><p><b>Example 2:</b></p><pre class="crayon-plain-tag">Input: nums = [1, 2, 3, 4]
Output: -1
Explanation: 4 isn't at least as big as twice the value of 3, so we return -1.</pre><p><b>Note:</b></p>
<ol>
<li><code>nums</code> will have a length in the range <code>[1, 50]</code>.</li>
<li>Every <code>nums[i]</code> will be an integer in the range <code>[0, 99]</code>.</li>
</ol>
<p><strong>Solution:</strong></p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 6 ms
class Solution {
public:
    int dominantIndex(vector&lt;int&gt;&amp; nums) {
        auto it1 = max_element(nums.begin(), nums.end());
        const int max1 = *it1;
        *it1 = -1;
        const int max2 = *max_element(nums.begin(), nums.end());
        return max1 &gt;= max2 * 2 ? distance(nums.begin(), it1) : -1;
    }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/difficulty/easy/leetcode-748-largest-number-at-least-twice-of-others/">花花酱 LeetCode 748. Largest Number At Least Twice of Others</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/difficulty/easy/leetcode-748-largest-number-at-least-twice-of-others/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 121. Best Time to Buy and Sell Stock</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-121-best-time-to-buy-and-sell-stock/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-121-best-time-to-buy-and-sell-stock/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 23 Dec 2017 01:32:19 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[Easy]]></category>
		<category><![CDATA[max subarray]]></category>
		<category><![CDATA[reduction]]></category>
		<category><![CDATA[stock]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1319</guid>

					<description><![CDATA[<p>题目大意: 给你一只股票每天的价格，如果只能做一次交易（一次买进一次卖出）问你最多能赚多少钱。 Problem: Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-121-best-time-to-buy-and-sell-stock/">花花酱 LeetCode 121. Best Time to Buy and Sell Stock</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/8pVhUpF1INw?feature=oembed" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen></iframe></p>
<p>题目大意: 给你一只股票每天的价格，如果只能做一次交易（一次买进一次卖出）问你最多能赚多少钱。</p>
<p><strong>Problem:</strong></p>
<p>Say you have an array for which the <i>i</i><sup>th</sup> element is the price of a given stock on day <i>i</i>.</p>
<p>If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.</p>
<p><b>Example 1:</b></p><pre class="crayon-plain-tag">Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)</pre><p><b>Example 2:</b></p><pre class="crayon-plain-tag">Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.</pre><p>&nbsp;</p>
<p><img class="alignnone size-full wp-image-1561" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/121-ep140-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/121-ep140-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/121-ep140-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/121-ep140-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p><strong>Idea:</strong></p>
<p>DP</p>
<p><strong>Solution 1:</strong></p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 6 ms
class Solution {
public:
    int maxProfit(vector&lt;int&gt;&amp; prices) {
        const int n = prices.size();
        if (n &lt; 1) return 0;
        vector&lt;int&gt; min_prices(n);
        vector&lt;int&gt; max_profit(n);
        min_prices[0] = prices[0];
        max_profit[0] = 0;
        for (int i = 1; i &lt; n; ++i) {
            min_prices[i] = min(min_prices[i - 1], 
                                prices[i]);
            
            max_profit[i] = max(max_profit[i - 1], 
                                prices[i] - min_prices[i - 1]);
        }
        return max_profit[n - 1];
    }
};</pre><p>C++ / reduce to maximum subarray</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 6 ms
class Solution {
public:
    int maxProfit(vector&lt;int&gt;&amp; prices) {
        int n = prices.size();
        if (n &lt; 2) return 0;
        vector&lt;int&gt; gains(n - 1, 0);
        for (int i = 1; i &lt; n; ++i)
            gains[i - 1] = prices[i] - prices[i - 1];
        return max(0, maxSubArray(gains));
    }
private:
    // From LC 53. Maximum Subarray
    int maxSubArray(vector&lt;int&gt;&amp; nums) {
        vector&lt;int&gt; f(nums.size());
        f[0] = nums[0];
        
        for (int i = 1; i &lt; nums.size(); ++i)
            f[i] = max(f[i - 1] + nums[i], nums[i]);
        
        return *std::max_element(f.begin(), f.end());
    }
};</pre><p><strong>Related Problems:</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/dynamic-programming/leetcode-309-best-time-to-buy-and-sell-stock-with-cooldown/">花花酱 LeetCode 309. Best Time to Buy and Sell Stock with Cooldown</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-121-best-time-to-buy-and-sell-stock/">花花酱 LeetCode 121. Best Time to Buy and Sell Stock</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/dynamic-programming/leetcode-121-best-time-to-buy-and-sell-stock/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 748. Shortest Completing Word</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-748-shortest-completing-word/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-748-shortest-completing-word/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 20 Dec 2017 16:23:52 +0000</pubDate>
				<category><![CDATA[Easy]]></category>
		<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[String]]></category>
		<category><![CDATA[frequency]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1294</guid>

					<description><![CDATA[<p>题目大意: 给你一个由字母和数字组成车牌。另外给你一些单词，让你找一个最短的单词能够覆盖住车牌中的字母（不考虑大小写）。如果有多个解，输出第一个解。 Problem: Find the minimum length word from a given dictionary words, which has all the letters from the string licensePlate. Such a word is said&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-748-shortest-completing-word/">花花酱 LeetCode 748. Shortest Completing Word</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/vHzPkqpPiWk?feature=oembed" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen></iframe></p>
<p>题目大意: 给你一个由字母和数字组成车牌。另外给你一些单词，让你找一个最短的单词能够覆盖住车牌中的字母（不考虑大小写）。如果有多个解，输出第一个解。</p>
<p><strong>Problem:</strong></p>
<p>Find the minimum length word from a given dictionary <code>words</code>, which has all the letters from the string <code>licensePlate</code>. Such a word is said to <i>complete</i> the given string <code>licensePlate</code></p>
<p>Here, for letters we ignore case. For example, <code>"P"</code> on the <code>licensePlate</code> still matches <code>"p"</code> on the word.</p>
<p>It is guaranteed an answer exists. If there are multiple answers, return the one that occurs first in the array.</p>
<p>The license plate might have the same letter occurring multiple times. For example, given a <code>licensePlate</code> of <code>"PP"</code>, the word <code>"pair"</code> does not complete the <code>licensePlate</code>, but the word <code>"supper"</code> does.</p>
<p><b>Example 1:</b></p><pre class="crayon-plain-tag">Input: licensePlate = &quot;1s3 PSt&quot;, words = [&quot;step&quot;, &quot;steps&quot;, &quot;stripe&quot;, &quot;stepple&quot;]
Output: &quot;steps&quot;
Explanation: The smallest length word that contains the letters &quot;S&quot;, &quot;P&quot;, &quot;S&quot;, and &quot;T&quot;.
Note that the answer is not &quot;step&quot;, because the letter &quot;s&quot; must occur in the word twice.
Also note that we ignored case for the purposes of comparing whether a letter exists in the word.</pre><p><b>Example 2:</b></p><pre class="crayon-plain-tag">Input: licensePlate = &quot;1s3 456&quot;, words = [&quot;looks&quot;, &quot;pest&quot;, &quot;stew&quot;, &quot;show&quot;]
Output: &quot;pest&quot;
Explanation: There are 3 smallest length words that contains the letters &quot;s&quot;.
We return the one that occurred first.</pre><p><b>Note:</b></p>
<ol>
<li><code>licensePlate</code> will be a string with length in range <code>[1, 7]</code>.</li>
<li><code>licensePlate</code> will contain digits, spaces, or letters (uppercase or lowercase).</li>
<li><code>words</code> will have a length in the range <code>[10, 1000]</code>.</li>
<li>Every <code>words[i]</code> will consist of lowercase letters, and have length in range <code>[1, 15]</code>.</li>
</ol>
<p><strong>Idea:</strong></p>
<p>Hashtable</p>
<p><strong>Solution:</strong></p>
<p>C++</p>
<p>Time complexity: 时间复杂度 O(N*26), N is number of words.</p>
<p>Space complexity: 空间复杂度 O(26) = O(1)</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 15 ms
class Solution {
public:
    string shortestCompletingWord(string licensePlate, vector&lt;string&gt;&amp; words) {
        vector&lt;int&gt; l(26, 0);
        for (const char ch : licensePlate)
            if (isalpha(ch)) ++l[tolower(ch) - 'a'];
        string ans;
        int min_l = INT_MAX;
        for (const string&amp; word : words) {
            if (word.length() &gt;= min_l) continue;
            if (!matches(l, word)) continue;
            min_l = word.length();
            ans = word;
        }
        return ans;
    }
private:
    bool matches(const vector&lt;int&gt;&amp; l, const string&amp; word) {
        vector&lt;int&gt; c(26, 0);
        for (const char ch : word)
            ++c[tolower(ch) - 'a'];        
        for (int i = 0; i &lt; 26; ++i)
            if (c[i] &lt; l[i]) return false;
        return true;
    }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-748-shortest-completing-word/">花花酱 LeetCode 748. Shortest Completing Word</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-748-shortest-completing-word/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 530. Minimum Absolute Difference in BST</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-530-minimum-absolute-difference-in-bst/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-530-minimum-absolute-difference-in-bst/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 09 Dec 2017 19:07:36 +0000</pubDate>
				<category><![CDATA[Easy]]></category>
		<category><![CDATA[Tree]]></category>
		<category><![CDATA[BST]]></category>
		<category><![CDATA[sorting]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1162</guid>

					<description><![CDATA[<p>Link Problem: Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes. Example: [crayon-663cb600dc1a5887381972/] Note: There are at least&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-530-minimum-absolute-difference-in-bst/">花花酱 LeetCode 530. Minimum Absolute Difference in BST</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><a href="https://leetcode.com/problems/minimum-absolute-difference-in-bst/">Link</a></p>
<p><iframe width="500" height="375" src="https://www.youtube.com/embed/0JHrHh_mIIw?feature=oembed" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen></iframe></p>
<p><strong>Problem:</strong></p>
<p>Given a binary search tree with non-negative values, find the minimum <a href="https://en.wikipedia.org/wiki/Absolute_difference">absolute difference</a> between values of any two nodes.</p>
<p><b>Example:</b></p><pre class="crayon-plain-tag">Input:

   1
    \
     3
    /
   2

Output:
1

Explanation:
The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).</pre><p><b>Note:</b> There are at least two nodes in this BST.</p>
<p><ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-2404451723245401" data-ad-slot="7983117522"></ins><br />
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<p><strong>Idea:</strong></p>
<p>Sorting via inorder traversal gives us sorted values, compare current one with previous one to reduce space complexity from O(n) to O(h).</p>
<p><img class="alignnone wp-image-1171 size-full" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/530-ep127.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/530-ep127.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/530-ep127-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/530-ep127-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p><strong>Solution:</strong></p>
<p>C++ O(n) space</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 19 ms
class Solution {
public:
    int getMinimumDifference(TreeNode* root) {
        std::vector&lt;int&gt; sorted;
        inorder(root, sorted);
        int min_diff = sorted.back();
        for (int i = 1; i &lt; sorted.size(); ++i)
            min_diff = min(min_diff, sorted[i] - sorted[i - 1]);
        return min_diff;
    }
private:
    void inorder(TreeNode* root, std::vector&lt;int&gt;&amp; sorted) {
        if (!root) return;
        inorder(root-&gt;left, sorted);
        sorted.push_back(root-&gt;val);
        inorder(root-&gt;right, sorted);
    }
};</pre><p>C++ O(h) space</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 16 ms
class Solution {
public:
    int getMinimumDifference(TreeNode* root) {
        min_diff_ = INT_MAX;
        prev_ = nullptr;
        inorder(root);
        return min_diff_;
    }
private:
    void inorder(TreeNode* root) {
        if (!root) return;
        inorder(root-&gt;left);
        if (prev_) min_diff_ = min(min_diff_, root-&gt;val - *prev_);
        prev_ = &amp;root-&gt;val;
        inorder(root-&gt;right);
    }
    
    int* prev_;
    int min_diff_;
};</pre><p>Java</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 16 ms
class Solution {
    public int getMinimumDifference(TreeNode root) {
        prev_ = null;
        min_diff_ = Integer.MAX_VALUE;
        inorder(root);
        return min_diff_;
    }
    
    private void inorder(TreeNode root) {
        if (root == null) return;
        inorder(root.left);
        if (prev_ != null) min_diff_ = Math.min(min_diff_, root.val - prev_);
        prev_ = root.val;
        inorder(root.right);
    }
    
    private Integer prev_;
    private int min_diff_;
}</pre><p>Python</p><pre class="crayon-plain-tag">"""
Author: Huahua
Runtime: 92 ms
"""
class Solution(object):
    def getMinimumDifference(self, root):        
        def inorder(root):
            if not root: return
            inorder(root.left)
            if self.prev is not None: self.min_diff = min(self.min_diff, root.val - self.prev)
            self.prev = root.val
            inorder(root.right)
        
        self.prev = None
        self.min_diff = float('inf')
        inorder(root)
        return self.min_diff</pre><p><strong>Related Problems:</strong></p>
<ul>
<li>[解题报告] LeetCode 98. Validate Binary Search Tree</li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-530-minimum-absolute-difference-in-bst/">花花酱 LeetCode 530. Minimum Absolute Difference in BST</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-530-minimum-absolute-difference-in-bst/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 198. House Robber</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-198-house-robber/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-198-house-robber/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 05 Dec 2017 16:35:09 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[Easy]]></category>
		<category><![CDATA[dp]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1112</guid>

					<description><![CDATA[<p>Problem: You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-198-house-robber/">花花酱 LeetCode 198. House Robber</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/H75Qp7ExCwo?feature=oembed" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen></iframe></p>
<p><strong>Problem:</strong></p>
<p>You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and <b>it will automatically contact the police if two adjacent houses were broken into on the same night</b>.</p>
<p>Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight <b>without alerting the police</b>.</p>
<p><strong>Idea:</strong></p>
<p>DP</p>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(n) -&gt; O(1)</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/198-ep124.png"><img class="alignnone size-full wp-image-1118" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/198-ep124.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/198-ep124.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/198-ep124-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/198-ep124-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p><strong>Solution:</strong></p>
<p>C++ / Recursion + Memorization</p>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(n)</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 0 ms
class Solution {
public:
    int rob(vector&lt;int&gt;&amp; nums) {
        const int n = nums.size();
        m_ = vector&lt;int&gt;(n, -1);
        return rob(nums, n - 1);
    }
private:
    int rob(const vector&lt;int&gt;&amp; nums, int i) {
        if (i &lt; 0) return 0;
        if (m_[i] &gt;= 0) return m_[i];
        return m_[i] = max(rob(nums, i - 2) + nums[i], 
                           rob(nums, i - 1));
    }
    
    vector&lt;int&gt; m_;
};</pre><p>&nbsp;</p>
<p>C++ / DP</p>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(n)</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 3 ms
class Solution {
public:
    int rob(vector&lt;int&gt;&amp; nums) {
        if (nums.empty()) return 0;
        vector&lt;int&gt; dp(nums.size(), 0);
        for (int i = 0; i &lt; nums.size() ; ++i)
            dp[i] = max((i &gt; 1 ? dp[i - 2] : 0) + nums[i], 
                        (i &gt; 0 ? dp[i - 1] : 0));
        return dp.back();
    }
};</pre><p>C++ / O(1) Space</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 3 ms
class Solution {
public:
    int rob(vector&lt;int&gt;&amp; nums) {
        if (nums.empty()) return 0;
        int dp2 = 0;
        int dp1 = 0;
        for (int i = 0; i &lt; nums.size() ; ++i) {
            int dp = max(dp2 + nums[i], dp1);
            dp2 = dp1;
            dp1 = dp;
        }
        return dp1;
    }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-198-house-robber/">花花酱 LeetCode 198. House Robber</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/dynamic-programming/leetcode-198-house-robber/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 734. Sentence Similarity</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-734-sentence-similarity/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-734-sentence-similarity/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 28 Nov 2017 22:17:26 +0000</pubDate>
				<category><![CDATA[Easy]]></category>
		<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[words]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1006</guid>

					<description><![CDATA[<p>Problem: Given two sentences words1, words2 (each represented as an array of strings), and a list of similar word pairs pairs, determine if two sentences are similar. For&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-734-sentence-similarity/">花花酱 LeetCode 734. Sentence Similarity</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/KAX277fYKMM?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p><strong>Problem:</strong></p>
<p>Given two sentences <code>words1, words2</code> (each represented as an array of strings), and a list of similar word pairs <code>pairs</code>, determine if two sentences are similar.</p>
<p>For example, &#8220;great acting skills&#8221; and &#8220;fine drama talent&#8221; are similar, if the similar word pairs are <code>pairs = [["great", "fine"], ["acting","drama"], ["skills","talent"]]</code>.</p>
<p>Note that the similarity relation is not transitive. For example, if &#8220;great&#8221; and &#8220;fine&#8221; are similar, and &#8220;fine&#8221; and &#8220;good&#8221; are similar, &#8220;great&#8221; and &#8220;good&#8221; are <b>not</b> necessarily similar.</p>
<p>However, similarity is symmetric. For example, &#8220;great&#8221; and &#8220;fine&#8221; being similar is the same as &#8220;fine&#8221; and &#8220;great&#8221; being similar.</p>
<p>Also, a word is always similar with itself. For example, the sentences <code>words1 = ["great"], words2 = ["great"], pairs = []</code> are similar, even though there are no specified similar word pairs.</p>
<p>Finally, sentences can only be similar if they have the same number of words. So a sentence like <code>words1 = ["great"]</code> can never be similar to <code>words2 = ["doubleplus","good"]</code>.</p>
<p><b>Note:</b></p>
<ul>
<li>The length of <code>words1</code> and <code>words2</code> will not exceed <code>1000</code>.</li>
<li>The length of <code>pairs</code> will not exceed <code>2000</code>.</li>
<li>The length of each <code>pairs[i]</code> will be <code>2</code>.</li>
<li>The length of each <code>words[i]</code> and <code>pairs[i][j]</code> will be in the range <code>[1, 20]</code>.</li>
</ul>
<p><ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-2404451723245401" data-ad-slot="7983117522"></ins><br />
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<p>题目大意：</p>
<p>给你两个句子（由单词数组表示）和一些近义词对，问你这两个句子是否相似，即每组相对应的单词都要相似。</p>
<p>注意相似性不能传递，比如给只你&#8221;great&#8221;和&#8221;fine&#8221;相似、&#8221;fine&#8221;和&#8221;good&#8221;相似，这种情况下&#8221;great&#8221;和&#8221;good&#8221;不相似。</p>
<p><strong>Idea:</strong></p>
<p>Use hashtable to store mapping from word to its similar words.</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/734-ep117.png"><img class="alignnone size-full wp-image-1028" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/734-ep117.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/734-ep117.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/734-ep117-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/734-ep117-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<h1><strong>Solution: HashTable</strong></h1>
<p>Time complexity: O(|pairs| + |words1|)</p>
<p>Space complexity: O(|pairs|)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 9 ms
class Solution {
public:
    bool areSentencesSimilar(vector&lt;string&gt;&amp; words1, vector&lt;string&gt;&amp; words2, vector&lt;pair&lt;string, string&gt;&gt; pairs) {
        if (words1.size() != words2.size()) return false;
        
        unordered_map&lt;string, unordered_set&lt;string&gt;&gt; similar_words;
        for (const auto&amp; pair : pairs) {            
            similar_words[pair.first].insert(pair.second);
            similar_words[pair.second].insert(pair.first);
        }
        
        for (int i = 0; i &lt; words1.size(); ++i) {
            if (words1[i] == words2[i]) continue;
            if (!similar_words[words1[i]].count(words2[i])) return false;
        }
        
        return true;
    }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 10 ms
class Solution {
    public boolean areSentencesSimilar(String[] words1, String[] words2, String[][] pairs) {
        if (words1.length != words2.length) return false;
        
        Map&lt;String, Set&lt;String&gt;&gt; similar_words = new HashMap&lt;&gt;();
        
        for (String[] pair : pairs) {
            if (!similar_words.containsKey(pair[0]))
                similar_words.put(pair[0], new HashSet&lt;&gt;());
            if (!similar_words.containsKey(pair[1]))
                similar_words.put(pair[1], new HashSet&lt;&gt;());
            similar_words.get(pair[0]).add(pair[1]);
            similar_words.get(pair[1]).add(pair[0]);
        }
        
        for (int i = 0; i &lt; words1.length; ++i) {
            if (words1[i].equals(words2[i])) continue;
            if (!similar_words.containsKey(words1[i])) return false;
            if (!similar_words.get(words1[i]).contains(words2[i])) return false;
        }
        
        return true;
    }
}</pre><p></div><h2 class="tabtitle">Python</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">"""
Author: Huahua
Runtime: 62 ms
"""
class Solution:
    def areSentencesSimilar(self, words1, words2, pairs):
        if len(words1) != len(words2): return False
        
        similar_words = {}
        
        for w1, w2 in pairs:
            if not w1 in similar_words: similar_words[w1] = set()
            if not w2 in similar_words: similar_words[w2] = set()
            similar_words[w1].add(w2)
            similar_words[w2].add(w1)
        
        for w1, w2 in zip(words1, words2):
            if w1 == w2: continue
            if w1 not in similar_words: return False
            if w2 not in similar_words[w1]: return False
        
        return True</pre><p></div></div></p>
<p><strong>Related Problems:</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/hashtable/leetcode-737-sentence-similarity-ii/">[解题报告] LeetCode 737. Sentence Similarity II</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-734-sentence-similarity/">花花酱 LeetCode 734. Sentence Similarity</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-734-sentence-similarity/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
