<?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>distance Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/distance/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/distance/</link>
	<description></description>
	<lastBuildDate>Mon, 04 May 2020 03:59:45 +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>distance Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/distance/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 1437. Check If All 1&#8217;s Are at Least Length K Places Away</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1437-check-if-all-1s-are-at-least-length-k-places-away/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1437-check-if-all-1s-are-at-least-length-k-places-away/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 04 May 2020 03:59:16 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[distance]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6698</guid>

					<description><![CDATA[<p>Given an array&#160;nums&#160;of 0s and 1s and an integer&#160;k, return&#160;True&#160;if all 1&#8217;s are at least&#160;k&#160;places away from each other, otherwise return&#160;False. Example 1: Input: nums&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1437-check-if-all-1s-are-at-least-length-k-places-away/">花花酱 LeetCode 1437. Check If All 1&#8217;s Are at Least Length K Places Away</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&nbsp;<code>nums</code>&nbsp;of 0s and 1s and an integer&nbsp;<code>k</code>, return&nbsp;<code>True</code>&nbsp;if all 1&#8217;s are at least&nbsp;<code>k</code>&nbsp;places away from each other, otherwise return&nbsp;<code>False</code>.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/04/15/sample_1_1791.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,0,0,0,1,0,0,1], k = 2
<strong>Output:</strong> true
<strong>Explanation:</strong> Each of the 1s are at least 2 places away from each other.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/04/15/sample_2_1791.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,0,0,1,0,1], k = 2
<strong>Output:</strong> false
<strong>Explanation: </strong>The second 1 and third 1 are only one apart from each other.</pre>



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



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



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



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



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



<ul><li><code>1 &lt;= nums.length &lt;= 10^5</code></li><li><code>0 &lt;= k &lt;= nums.length</code></li><li><code>nums[i]</code>&nbsp;is&nbsp;<code>0</code>&nbsp;or&nbsp;<code>1</code></li></ul>



<h2><strong>Solution: Scan the array</strong></h2>



<p>Only need to check adjacent ones. This problem should be easy instead of medium.</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 kLengthApart(vector&lt;int&gt;&amp; nums, int k) {
    int d = k + 1; // distant enough
    for (int n : nums) {
      if (n == 0) {
        ++d;
      } else {
        if (d &lt; k) return false;
        d = 0;
      }
    }
    return true;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1437-check-if-all-1s-are-at-least-length-k-places-away/">花花酱 LeetCode 1437. Check If All 1&#8217;s Are at Least Length K Places Away</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-1437-check-if-all-1s-are-at-least-length-k-places-away/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 821. Shortest Distance to a Character</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-821-shortest-distance-to-a-character/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-821-shortest-distance-to-a-character/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 22 Apr 2018 16:58:22 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[distance]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2753</guid>

					<description><![CDATA[<p>Problem 题目大意：输出字符串的每个字符到一个指定字符的对短距离。 https://leetcode.com/problems/shortest-distance-to-a-character/description/ Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string. Example 1: Input:&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-821-shortest-distance-to-a-character/">花花酱 LeetCode 821. Shortest Distance to a Character</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>
<h1><strong>Problem</strong></h1>
<p>题目大意：输出字符串的每个字符到一个指定字符的对短距离。</p>
<p><a href="https://leetcode.com/problems/shortest-distance-to-a-character/description/">https://leetcode.com/problems/shortest-distance-to-a-character/description/</a></p>
<p>Given a string <code>S</code> and a character <code>C</code>, return an array of integers representing the shortest distance from the character <code>C</code> in the string.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> S = "loveleetcode", C = 'e'
<strong>Output:</strong> [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
</pre>
<p>&nbsp;</p>
<p><strong>Note:</strong></p>
<ol>
<li><code>S</code> string length is in <code>[1, 10000].</code></li>
<li><code>C</code> is a single character, and guaranteed to be in string <code>S</code>.</li>
<li>All letters in <code>S</code> and <code>C</code> are lowercase.</li>
</ol>
</div>
<h1><strong>Solution: Two Pass</strong></h1>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(n)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 14 ms
class Solution {
public:
  vector&lt;int&gt; shortestToChar(string S, char C) {
    const int n = S.length();
    vector&lt;int&gt; ans(n, INT_MAX);
    int index = -1;
    for (int i = 0; i &lt; n; ++i) {
      if (S[i] == C) index = i;
      if (index &lt; 0) continue;
      ans[i] = abs(i - index);
    }
    index = -1;
    for (int i = n - 1; i &gt;= 0; --i) {
      if (S[i] == C) index = i;
      if (index &lt; 0) continue;
      ans[i] = min(ans[i], abs(i - index));
    }
    return ans;
  }
};</pre><p>V2</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 14 ms
class Solution {
public:
  vector&lt;int&gt; shortestToChar(string S, char C) {
    const int n = S.length();
    vector&lt;int&gt; indices(2 * n); // 0, 1, ..., n - 1, n - 1, n - 2, ..., 0
    std::iota(indices.begin(), indices.begin() + n, 0);
    std::iota(indices.rbegin(), indices.rbegin() + n, 0);
    vector&lt;int&gt; ans(n, INT_MAX);
    int index = -n;
    for (int i : indices) {
      if (S[i] == C) index = i;
      ans[i] = min(ans[i], abs(i - index));
    }
    return ans;
  }
};</pre><p>&nbsp;</p>
</div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-821-shortest-distance-to-a-character/">花花酱 LeetCode 821. Shortest Distance to a Character</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-821-shortest-distance-to-a-character/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 447. Number of Boomerangs</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-447-number-of-boomerangs/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-447-number-of-boomerangs/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 24 Mar 2018 19:11:52 +0000</pubDate>
				<category><![CDATA[Geometry]]></category>
		<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[distance]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[pairs]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2347</guid>

					<description><![CDATA[<p>Problem Given n points in the plane that are all pairwise distinct, a &#8220;boomerang&#8221; is a tuple of points (i, j, k) such that the distance between i and j equals the distance&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-447-number-of-boomerangs/">花花酱 LeetCode 447. Number of Boomerangs</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>Problem</h1>
<div class="question-description">
<div>
<p>Given <i>n</i> points in the plane that are all pairwise distinct, a &#8220;boomerang&#8221; is a tuple of points <code>(i, j, k)</code> such that the distance between <code>i</code> and <code>j</code> equals the distance between <code>i</code> and <code>k</code> (<b>the order of the tuple matters</b>).</p>
<p>Find the number of boomerangs. You may assume that <i>n</i> will be at most <b>500</b> and coordinates of points are all in the range <b>[-10000, 10000]</b> (inclusive).</p>
<p><b>Example:</b></p>
<pre class="crayon:false"><b>Input:</b>
[[0,0],[1,0],[2,0]]

<b>Output:</b>
2

<b>Explanation:</b>
The two boomerangs are <b>[[1,0],[0,0],[2,0]]</b> and <b>[[1,0],[2,0],[0,0]]</b>
</pre>
</div>
</div>
<h1><strong>Solution: HashTable</strong></h1>
<p>For each point, compute the distance to the rest of the points and count.</p>
<p>if there are k points that have the same distance to current point, then there are P(k,2) = k*k-1 Boomerangs.</p>
<p>for example, p1, p2, p3 have the same distance to p0, then there are P(3,2) = 3 * (3-1) = 6 Boomerangs</p>
<p>(p1, p0, p2), (p1, p0, p3)</p>
<p>(p2, p0, p1), (p2, p0, p3)</p>
<p>(p3, p0, p1), (p3, p0, p2)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 210 ms (beats 83.33%)
class Solution {
public:
  int numberOfBoomerangs(vector&lt;pair&lt;int, int&gt;&gt;&amp; points) {
    int ans = 0;
    for (int i = 0; i &lt; points.size(); ++i) {
      unordered_map&lt;int, int&gt; dist(points.size());
      for (int j = 0; j &lt; points.size(); ++j) {
        const int dx = points[i].first - points[j].first;
        const int dy = points[i].second - points[j].second;        
        ++dist[dx * dx + dy * dy];
      }
      for (const auto&amp; kv : dist)
        ans += kv.second * (kv.second - 1);      
    }
    return ans;
  }
};</pre><p></p>
<h2><strong>Solution 2: Sorting</strong></h2>
<p>dist = [1, 2, 1, 2, 1, 5]</p>
<p>sorted_dist = [1, 1, 1, 2, 2, 5], 1*3, 2*2, 5*1</p>
<p>ans = 3*(3-1) + 2 * (2 &#8211; 1) * 1 * (1 &#8211; 1) = 8</p>
<p>Time complexity: O(n*nlogn)</p>
<p>Space complexity: O(n)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 150 ms (beats 98.52%)
class Solution {
public:
  int numberOfBoomerangs(vector&lt;pair&lt;int, int&gt;&gt;&amp; points) {
    const int n = points.size();
    int ans = 0;
    vector&lt;int&gt; dist(points.size());
    for (int i = 0; i &lt; n; ++i) {   
      for (int j = 0; j &lt; n; ++j) {
        const int dx = points[i].first - points[j].first;
        const int dy = points[i].second - points[j].second;    
        dist[j] = dx * dx + dy * dy;
      }
      
      std::sort(dist.begin(), dist.end());
      
      for (int j = 1; j &lt; n; ++j) {
        int k = 1;
        while (j &lt; n &amp;&amp; dist[j] == dist[j - 1]) { ++j; ++k; }
        ans += k * (k - 1);
      }
    }
    return ans;
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-447-number-of-boomerangs/">花花酱 LeetCode 447. Number of Boomerangs</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-447-number-of-boomerangs/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 477. Total Hamming Distance</title>
		<link>https://zxi.mytechroad.com/blog/bit/leetcode-477-total-hamming-distance/</link>
					<comments>https://zxi.mytechroad.com/blog/bit/leetcode-477-total-hamming-distance/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 15 Dec 2017 02:36:14 +0000</pubDate>
				<category><![CDATA[Bit]]></category>
		<category><![CDATA[bit]]></category>
		<category><![CDATA[distance]]></category>
		<category><![CDATA[hamming]]></category>
		<category><![CDATA[mask]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1243</guid>

					<description><![CDATA[<p>Problem: The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Now your job is to find the total&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-477-total-hamming-distance/">花花酱 LeetCode 477. Total Hamming Distance</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">
<p><iframe width="500" height="375" src="https://www.youtube.com/embed/fH9clXXrS2Q?feature=oembed" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen></iframe></p>
<p><strong>Problem:</strong></p>
<p>The <a href="https://en.wikipedia.org/wiki/Hamming_distance" target="_blank" rel="noopener">Hamming distance</a> between two integers is the number of positions at which the corresponding bits are different.</p>
<p>Now your job is to find the total Hamming distance between all pairs of the given numbers.</p>
<p><b>Example:</b></p><pre class="crayon-plain-tag">Input: 4, 14, 2

Output: 6

Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just
showing the four bits relevant in this case). So the answer will be:
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.</pre><p><b>Note:</b></p>
<ol>
<li>Elements of the given array are in the range of <code>0 </code>to <code>10^9</code></li>
<li>Length of the array will not exceed <code>10^4</code>.</li>
</ol>
<p><strong>题目大意：</strong>给你一堆数，让你求所有数对的HammingDistance的总和。</p>
<p><strong>Idea:</strong></p>
<ol>
<li>Brute force, compute HammingDistance for all pairs. O(n^2) TLE</li>
<li>Count how many ones on i-th bit, assuming k. Distance += k * (n &#8211; k). O(n)</li>
</ol>
<p><img class="alignnone size-full wp-image-1248" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/477-ep132.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/477-ep132.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/477-ep132-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/477-ep132-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
</div>
<p><strong>Solution:</strong></p>
<p>C++ / O(n)</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 59 ms
class Solution {
public:
    int totalHammingDistance(vector&lt;int&gt;&amp; nums) {
        int ans = 0;
        int mask = 1;
        for (int i = 0; i &lt; 32; ++i) {
            int count = 0;
            for (const int num : nums)
                if (num &amp; mask) ++count;
            ans += (nums.size() - count) * count;
            mask &lt;&lt;= 1;
        }
        return ans;
    }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/bit/leetcode-477-total-hamming-distance/">花花酱 LeetCode 477. Total Hamming Distance</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/bit/leetcode-477-total-hamming-distance/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 719. Find K-th Smallest Pair Distance</title>
		<link>https://zxi.mytechroad.com/blog/divide-and-conquer/leetcode-719-find-k-th-smallest-pair-distance/</link>
					<comments>https://zxi.mytechroad.com/blog/divide-and-conquer/leetcode-719-find-k-th-smallest-pair-distance/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 29 Oct 2017 20:14:10 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[Divide and conquer]]></category>
		<category><![CDATA[Hard]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[bucket]]></category>
		<category><![CDATA[distance]]></category>
		<category><![CDATA[pair]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=710</guid>

					<description><![CDATA[<p>题目大意：给你一个数组，返回所有数对中，绝对值差第k小的值。 Problem: Given an integer array, return the k-th smallest distance among all the pairs. The distance of a pair (A, B) is defined as the absolute&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/divide-and-conquer/leetcode-719-find-k-th-smallest-pair-distance/">花花酱 LeetCode 719. Find K-th Smallest Pair Distance</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/WHfljqX61Y8?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p>题目大意：给你一个数组，返回所有数对中，绝对值差第k小的值。</p>
<p><strong>Problem:</strong></p>
<p>Given an integer array, return the k-th smallest <b>distance</b> among all the pairs. The distance of a pair (A, B) is defined as the absolute difference between A and B.</p>
<p><b>Example 1:</b></p><pre class="crayon-plain-tag">Input:
nums = [1,3,1]
k = 1
Output: 0 
Explanation:
Here are all the pairs:
(1,3) -&gt; 2
(1,1) -&gt; 0
(3,1) -&gt; 2
Then the 1st smallest distance pair is (1,1), and its distance is 0.</pre><p><b>Note:</b></p>
<ol>
<li><code>2 &lt;= len(nums) &lt;= 10000</code>.</li>
<li><code>0 &lt;= nums[i] &lt; 1000000</code>.</li>
<li><code>1 &lt;= k &lt;= len(nums) * (len(nums) - 1) / 2</code>.</li>
</ol>
<p><strong>Idea</strong></p>
<p>Bucket sort</p>
<p>Binary search / dp</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/719-ep99-1.png"><img class="alignnone size-full wp-image-720" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/719-ep99-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/719-ep99-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/719-ep99-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/719-ep99-1-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/719-ep99-1-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/719-ep99-2.png"><img class="alignnone size-full wp-image-719" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/719-ep99-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/719-ep99-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/719-ep99-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/719-ep99-2-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/719-ep99-2-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p><strong>Solution</strong></p>
<p>C++ / binary search</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 9 ms
class Solution {
public:
    int smallestDistancePair(vector&lt;int&gt;&amp; nums, int k) {
        std::sort(nums.begin(), nums.end());
        int n = nums.size();
        int l = 0;
        int r = nums.back() - nums.front();
        while (l &lt;= r) {
            int cnt = 0;
            int j = 0;
            int m = l + (r - l) / 2;
            for (int i = 0; i &lt; n; ++i) {
                while (j &lt; n &amp;&amp; nums[j] - nums[i] &lt;= m) ++j;
                cnt += j - i - 1;
            }
            cnt &gt;= k ? r = m - 1 : l = m + 1;
        }        
        return l;
    }
};</pre><p>&nbsp;</p>
<p>C++ / bucket sort w/ vector O(n^2)</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 549 ms
class Solution {
public:
    int smallestDistancePair(vector&lt;int&gt;&amp; nums, int k) {
        std::sort(nums.begin(), nums.end());
        const int N = nums.back();
        vector&lt;int&gt; count(N + 1, 0);        
        const int n = nums.size();
        for (int i = 0; i &lt; n; ++i)
            for (int j = i + 1; j &lt; n; ++j)
               ++count[nums[j] - nums[i]];
        for (int i = 0; i &lt;= N; ++i) {
            k -= count[i];
            if (k &lt;= 0) return i;
        }
        return 0;
    }
};</pre><p><strong>Related Problems:</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/two-pointers/leetcode-786-k-th-smallest-prime-fraction/">花花酱 LeetCode 786. K-th Smallest Prime Fraction</a></li>
<li><a href="http://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-378-kth-smallest-element-in-a-sorted-matrix/">花花酱 LeetCode 378. Kth Smallest Element in a Sorted Matrix</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/divide-and-conquer/leetcode-719-find-k-th-smallest-pair-distance/">花花酱 LeetCode 719. Find K-th Smallest Pair Distance</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/divide-and-conquer/leetcode-719-find-k-th-smallest-pair-distance/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 72. Edit Distance</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-72-edit-distance/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-72-edit-distance/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 15 Oct 2017 17:29:41 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[distance]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=596</guid>

					<description><![CDATA[<p>Problem: Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.) You have the following 3&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-72-edit-distance/">花花酱 LeetCode 72. Edit Distance</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/Q4i_rqON2-E?feature=oembed" frameborder="0" gesture="media" allowfullscreen></iframe></p>
<p><strong>Problem:</strong></p>
<p>Given two words <i>word1</i> and <i>word2</i>, find the minimum number of steps required to convert <i>word1</i> to <i>word2</i>. (each operation is counted as 1 step.)</p>
<p>You have the following 3 operations permitted on a word:</p>
<p>a) Insert a character<br />
b) Delete a character<br />
c) Replace a character</p>
<p><strong>Idea:</strong></p>
<p>Dynamic Programming</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/72-ep87.png"><img class="alignnone size-full wp-image-602" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/72-ep87.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/72-ep87.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/72-ep87-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/72-ep87-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/72-ep87-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p><strong>Solution:</strong></p>
<p>Recursive</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 13 ms
class Solution {
public:
    int minDistance(string word1, string word2) {
        int l1 = word1.length();
        int l2 = word2.length();
        d_ = vector&lt;vector&lt;int&gt;&gt;(l1 + 1, vector&lt;int&gt;(l2 + 1, -1));
        return minDistance(word1, word2, l1, l2);
    }
private:
    vector&lt;vector&lt;int&gt;&gt; d_;
    // minDistance from word1[0:l1-1] to word2[0:l2-1]
    int minDistance(const string&amp; word1, const string&amp; word2, int l1, int l2) {
        if (l1 == 0) return l2;
        if (l2 == 0) return l1;
        if (d_[l1][l2] &gt;= 0) return d_[l1][l2];
        
        int ans;
        if (word1[l1 - 1] == word2[l2 - 1])
            ans = minDistance(word1, word2, l1 - 1, l2 - 1);
        else 
            ans = min(minDistance(word1, word2, l1 - 1, l2 - 1),
                  min(minDistance(word1, word2, l1 - 1, l2), 
                      minDistance(word1, word2, l1, l2 - 1))) + 1;
        
        return d_[l1][l2] = ans;        
    }
};</pre><p>Iterative</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 9 ms
class Solution {
public:
    int minDistance(string word1, string word2) {
        int l1 = word1.length();
        int l2 = word2.length();
        // d[i][j] := minDistance(word1[0:i - 1], word2[0:j - 1]);
        vector&lt;vector&lt;int&gt;&gt; d(l1 + 1, vector&lt;int&gt;(l2 + 1, 0));
        
        for (int i = 0; i &lt;= l1; ++i)
            d[i][0] = i;
        for (int j = 0; j &lt;= l2; ++j)
            d[0][j] = j;
        
        for (int i = 1; i &lt;= l1; ++i)
            for (int j = 1; j &lt;= l2; ++j) {
                int c = (word1[i - 1] == word2[j - 1]) ? 0 : 1;
                d[i][j] = min(d[i - 1][j - 1] + c, 
                              min(d[i][j - 1], d[i - 1][j]) + 1);
            }
        
        return d[l1][l2];
    }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-72-edit-distance/">花花酱 LeetCode 72. Edit Distance</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-72-edit-distance/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
