<?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>pair Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/pair/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/pair/</link>
	<description></description>
	<lastBuildDate>Sun, 13 Aug 2023 21:41:17 +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>pair Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/pair/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2815. Max Pair Sum in an Array</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2815-max-pair-sum-in-an-array/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2815-max-pair-sum-in-an-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 13 Aug 2023 21:40:33 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[digit]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[pair]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10067</guid>

					<description><![CDATA[<p>You are given a&#160;0-indexed&#160;integer array&#160;nums. You have to find the&#160;maximum&#160;sum of a pair of numbers from&#160;nums&#160;such that the maximum&#160;digit&#160;in both numbers are equal. Return&#160;the maximum&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2815-max-pair-sum-in-an-array/">花花酱 LeetCode 2815. Max Pair Sum in an Array</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>nums</code>. You have to find the&nbsp;<strong>maximum</strong>&nbsp;sum of a pair of numbers from&nbsp;<code>nums</code>&nbsp;such that the maximum&nbsp;<strong>digit&nbsp;</strong>in both numbers are equal.</p>



<p>Return&nbsp;<em>the maximum sum or</em>&nbsp;<code>-1</code><em>&nbsp;if no such pair exists</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [51,71,17,24,42]
<strong>Output:</strong> 88
<strong>Explanation:</strong> 
For i = 1 and j = 2, nums[i] and nums[j] have equal maximum digits with a pair sum of 71 + 17 = 88. 
For i = 3 and j = 4, nums[i] and nums[j] have equal maximum digits with a pair sum of 24 + 42 = 66.
It can be shown that there are no other pairs with equal maximum digits, so the answer is 88.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,3,4]
<strong>Output:</strong> -1
<strong>Explanation:</strong> No pair exists in nums with equal maximum digits.
</pre>



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



<ul><li><code>2 &lt;= nums.length &lt;= 100</code></li><li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li></ul>



<h2><strong>Solution: Brute Force</strong></h2>



<p>Enumerate all pairs of nums and check their sum and max digit.</p>



<p>Time complexity: O(n<sup>2</sup>)<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:
  int maxSum(vector&lt;int&gt;&amp; nums) {
    auto maxDigit = [](int x) {
      int ans = 0;
      while (x) {
        ans = max(ans, x % 10);
        x /= 10;
      }
      return ans;
    };
    int ans = -1;
    const int n = nums.size();
    for (int i = 0; i &lt; n; ++i)
      for (int j = i + 1; j &lt; n; ++j)
        if (nums[i] + nums[j] &gt; ans 
            &amp;&amp; maxDigit(nums[i]) == maxDigit(nums[j]))
          ans = nums[i] + nums[j];
    return ans;
  }
};</pre>
</div></div>

<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2815-max-pair-sum-in-an-array/">花花酱 LeetCode 2815. Max Pair Sum in an Array</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2815-max-pair-sum-in-an-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2563. Count the Number of Fair Pairs</title>
		<link>https://zxi.mytechroad.com/blog/two-pointers/leetcode-2563-count-the-number-of-fair-pairs/</link>
					<comments>https://zxi.mytechroad.com/blog/two-pointers/leetcode-2563-count-the-number-of-fair-pairs/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 12 Feb 2023 16:28:04 +0000</pubDate>
				<category><![CDATA[Two pointers]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[pair]]></category>
		<category><![CDATA[two pointers]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9939</guid>

					<description><![CDATA[<p>Given a&#160;0-indexed&#160;integer array&#160;nums&#160;of size&#160;n&#160;and two integers&#160;lower&#160;and&#160;upper, return&#160;the number of fair pairs. A pair&#160;(i, j)&#160;is&#160;fair&#160;if: 0 &#60;= i &#60; j &#60; n, and lower &#60;= nums[i]&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-2563-count-the-number-of-fair-pairs/">花花酱 LeetCode 2563. Count the Number of Fair Pairs</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>nums</code>&nbsp;of size&nbsp;<code>n</code>&nbsp;and two integers&nbsp;<code>lower</code>&nbsp;and&nbsp;<code>upper</code>, return&nbsp;<em>the number of fair pairs</em>.</p>



<p>A pair&nbsp;<code>(i, j)</code>&nbsp;is&nbsp;<strong>fair&nbsp;</strong>if:</p>



<ul><li><code>0 &lt;= i &lt; j &lt; n</code>, and</li><li><code>lower &lt;= nums[i] + nums[j] &lt;= upper</code></li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [0,1,7,4,4,5], lower = 3, upper = 6
<strong>Output:</strong> 6
<strong>Explanation:</strong> There are 6 fair pairs: (0,3), (0,4), (0,5), (1,3), (1,4), and (1,5).
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,7,9,2,5], lower = 11, upper = 11
<strong>Output:</strong> 1
<strong>Explanation:</strong> There is a single fair pair: (2,3).
</pre>



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



<ul><li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li><li><code>nums.length == n</code></li><li><code>-10<sup>9</sup>&nbsp;&lt;= nums[i] &lt;= 10<sup>9</sup></code></li><li><code>-10<sup>9</sup>&nbsp;&lt;= lower &lt;= upper &lt;= 10<sup>9</sup></code></li></ul>



<h2><strong>Solution: Two Pointers</strong></h2>



<p>Sort the array, use two pointers to find how # of pairs (i, j) s.t. nums[i] + nums[j] &lt;= limit.<br>Ans = count(upper) &#8211; count(lower &#8211; 1)</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:
  long long countFairPairs(vector&lt;int&gt;&amp; nums, int lower, int upper) {
    sort(begin(nums), end(nums));
    auto count = [&amp;](int limit) -&gt; long long {
      long long ans = 0;
      for (int i = 0, j = nums.size() - 1; i &lt; j; ++i) {
        while (i &lt; j &amp;&amp; nums[i] + nums[j] &gt; limit) --j;
        ans += j - i;
      }
      return ans;
    };
    return count(upper) - count(lower - 1);
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-2563-count-the-number-of-fair-pairs/">花花酱 LeetCode 2563. Count the Number of Fair Pairs</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/two-pointers/leetcode-2563-count-the-number-of-fair-pairs/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1913. Maximum Product Difference Between Two Pairs</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-1913-maximum-product-difference-between-two-pairs/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-1913-maximum-product-difference-between-two-pairs/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 25 Dec 2021 03:02:32 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[pair]]></category>
		<category><![CDATA[sorting]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9227</guid>

					<description><![CDATA[<p>The&#160;product difference&#160;between two pairs&#160;(a, b)&#160;and&#160;(c, d)&#160;is defined as&#160;(a * b) - (c * d). For example, the product difference between&#160;(5, 6)&#160;and&#160;(2, 7)&#160;is&#160;(5 * 6) -&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1913-maximum-product-difference-between-two-pairs/">花花酱 LeetCode 1913. Maximum Product Difference Between Two Pairs</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>The&nbsp;<strong>product difference</strong>&nbsp;between two pairs&nbsp;<code>(a, b)</code>&nbsp;and&nbsp;<code>(c, d)</code>&nbsp;is defined as&nbsp;<code>(a * b) - (c * d)</code>.</p>



<ul><li>For example, the product difference between&nbsp;<code>(5, 6)</code>&nbsp;and&nbsp;<code>(2, 7)</code>&nbsp;is&nbsp;<code>(5 * 6) - (2 * 7) = 16</code>.</li></ul>



<p>Given an integer array&nbsp;<code>nums</code>, choose four&nbsp;<strong>distinct</strong>&nbsp;indices&nbsp;<code>w</code>,&nbsp;<code>x</code>,&nbsp;<code>y</code>, and&nbsp;<code>z</code>&nbsp;such that the&nbsp;<strong>product difference</strong>&nbsp;between pairs&nbsp;<code>(nums[w], nums[x])</code>&nbsp;and&nbsp;<code>(nums[y], nums[z])</code>&nbsp;is&nbsp;<strong>maximized</strong>.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>maximum</strong>&nbsp;such product difference</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [5,6,2,7,4]
<strong>Output:</strong> 34
<strong>Explanation:</strong> We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).
The product difference is (6 * 7) - (2 * 4) = 34.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [4,2,5,9,7,4,8]
<strong>Output:</strong> 64
<strong>Explanation:</strong> We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).
The product difference is (9 * 8) - (2 * 4) = 64.
</pre>



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



<ul><li><code>4 &lt;= nums.length &lt;= 10<sup>4</sup></code></li><li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li></ul>



<h2><strong>Solution: Greedy</strong></h2>



<p>Since all the numbers are positive, we just need to find the largest two numbers as the first pair and smallest two numbers are the second pair.</p>



<p>Time complexity: O(nlogn) / sorting, O(n) / finding min/max elements.<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:
  int maxProductDifference(vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();
    sort(begin(nums), end(nums));
    return nums[n - 1] * nums[n - 2] - nums[0] * nums[1];
  }
};</pre>

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

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def maxProductDifference(self, nums: List[int]) -&gt; int:
    nums.sort()
    return nums[-1] * nums[-2] - nums[0] * nums[1]</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1913-maximum-product-difference-between-two-pairs/">花花酱 LeetCode 1913. Maximum Product Difference Between Two Pairs</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/greedy/leetcode-1913-maximum-product-difference-between-two-pairs/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1877. Minimize Maximum Pair Sum in Array</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-1877-minimize-maximum-pair-sum-in-array/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-1877-minimize-maximum-pair-sum-in-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 07 Aug 2021 06:23:24 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[pair]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8503</guid>

					<description><![CDATA[<p>The&#160;pair sum&#160;of a pair&#160;(a,b)&#160;is equal to&#160;a + b. The&#160;maximum pair sum&#160;is the largest&#160;pair sum&#160;in a list of pairs. For example, if we have pairs&#160;(1,5),&#160;(2,3), and&#160;(4,4),&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1877-minimize-maximum-pair-sum-in-array/">花花酱 LeetCode 1877. Minimize Maximum Pair Sum in Array</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>The&nbsp;<strong>pair sum</strong>&nbsp;of a pair&nbsp;<code>(a,b)</code>&nbsp;is equal to&nbsp;<code>a + b</code>. The&nbsp;<strong>maximum pair sum</strong>&nbsp;is the largest&nbsp;<strong>pair sum</strong>&nbsp;in a list of pairs.</p>



<ul><li>For example, if we have pairs&nbsp;<code>(1,5)</code>,&nbsp;<code>(2,3)</code>, and&nbsp;<code>(4,4)</code>, the&nbsp;<strong>maximum pair sum</strong>&nbsp;would be&nbsp;<code>max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8</code>.</li></ul>



<p>Given an array&nbsp;<code>nums</code>&nbsp;of&nbsp;<strong>even</strong>&nbsp;length&nbsp;<code>n</code>, pair up the elements of&nbsp;<code>nums</code>&nbsp;into&nbsp;<code>n / 2</code>&nbsp;pairs such that:</p>



<ul><li>Each element of&nbsp;<code>nums</code>&nbsp;is in&nbsp;<strong>exactly one</strong>&nbsp;pair, and</li><li>The&nbsp;<strong>maximum pair sum&nbsp;</strong>is&nbsp;<strong>minimized</strong>.</li></ul>



<p>Return&nbsp;<em>the minimized&nbsp;<strong>maximum pair sum</strong>&nbsp;after optimally pairing up the elements</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [3,5,2,3]
<strong>Output:</strong> 7
<strong>Explanation:</strong> The elements can be paired up into pairs (3,3) and (5,2).
The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [3,5,4,2,4,6]
<strong>Output:</strong> 8
<strong>Explanation:</strong> The elements can be paired up into pairs (3,5), (4,4), and (6,2).
The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8.
</pre>



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



<ul><li><code>n == nums.length</code></li><li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li><li><code>n</code>&nbsp;is&nbsp;<strong>even</strong>.</li><li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li></ul>



<h2><strong>Solution: Greedy</strong></h2>



<p>Sort the elements, pair nums[i] with nums[n &#8211; i &#8211; 1] and find the max pair.</p>



<p>Time complexity: O(nlogn) -&gt; O(n) counting sort.<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:
  int minPairSum(vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();
    int ans = 0;
    sort(begin(nums), end(nums));
    for (int i = 0; i &lt; n / 2; ++i)
      ans = max(ans, nums[i] + nums[n - i - 1]);
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1877-minimize-maximum-pair-sum-in-array/">花花酱 LeetCode 1877. Minimize Maximum Pair Sum in Array</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/greedy/leetcode-1877-minimize-maximum-pair-sum-in-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 981. Time Based Key-Value Store</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-981-time-based-key-value-store/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-981-time-based-key-value-store/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 27 Jan 2019 05:49:45 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[kv]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[pair]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4691</guid>

					<description><![CDATA[<p>Create a timebased key-value store class&#160;TimeMap, that supports two operations. 1.&#160;set(string key, string value, int timestamp) Stores the&#160;key&#160;and&#160;value, along with the given&#160;timestamp. 2.&#160;get(string key, int&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-981-time-based-key-value-store/">花花酱 LeetCode 981. Time Based Key-Value Store</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>Create a timebased key-value store class&nbsp;<code>TimeMap</code>, that supports two operations.</p>



<p>1.&nbsp;<code>set(string key, string value, int timestamp)</code></p>



<ul><li>Stores the&nbsp;<code>key</code>&nbsp;and&nbsp;<code>value</code>, along with the given&nbsp;<code>timestamp</code>.</li></ul>



<p>2.&nbsp;<code>get(string key, int timestamp)</code></p>



<ul><li>Returns a value such that&nbsp;<code>set(key, value, timestamp_prev)</code>&nbsp;was called previously, with&nbsp;<code>timestamp_prev &lt;= timestamp</code>.</li><li>If there are multiple such values, it returns the one with the largest&nbsp;<code>timestamp_prev</code>.</li><li>If there are no values, it returns the empty string (<code>""</code>).</li></ul>



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



<pre class="wp-block-preformatted crayon:false"><strong>Input: </strong>inputs = ["TimeMap","set","get","get","set","get","get"], inputs = [[],["foo","bar",1],["foo",1],["foo",3],["foo","bar2",4],["foo",4],["foo",5]]
<strong>Output: </strong>[null,null,"bar","bar",null,"bar2","bar2"]
<strong>Explanation: </strong>&nbsp; 
TimeMap kv; &nbsp; 
kv.set("foo", "bar", 1); // store the key "foo" and value "bar" along with timestamp = 1 &nbsp; 
kv.get("foo", 1);  // output "bar" &nbsp; 
kv.get("foo", 3); // output "bar" since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 ie "bar" &nbsp; 
kv.set("foo", "bar2", 4); &nbsp; 
kv.get("foo", 4); // output "bar2" &nbsp; 
kv.get("foo", 5); //output "bar2" &nbsp; 

</pre>



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



<pre class="wp-block-preformatted crayon:false"><strong>Input: </strong>inputs = ["TimeMap","set","set","get","get","get","get","get"], inputs = [[],["love","high",10],["love","low",20],["love",5],["love",10],["love",15],["love",20],["love",25]]
<strong>Output: </strong>[null,null,null,"","high","high","low","low"]
</pre>



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



<ol><li>All key/value strings are lowercase.</li><li>All key/value strings have&nbsp;length in the range&nbsp;<code>[1, 100]</code></li><li>The&nbsp;<code>timestamps</code>&nbsp;for all&nbsp;<code>TimeMap.set</code>&nbsp;operations are strictly increasing.</li><li><code>1 &lt;= timestamp &lt;= 10^7</code></li><li><code>TimeMap.set</code>&nbsp;and&nbsp;<code>TimeMap.get</code>&nbsp;functions will be called a total of&nbsp;<code>120000</code>&nbsp;times (combined) per test case.</li></ol>



<h2>Solution: HashTable + Map</h2>



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

<pre class="crayon-plain-tag">// Author: Huahua, running time: 200 ms
class TimeMap {
public:
  /** Initialize your data structure here. */
  TimeMap() {}

  void set(string key, string value, int timestamp) {
    s_[key].emplace(timestamp, std::move(value));
  }

  string get(string key, int timestamp) {
    auto m = s_.find(key);
    if (m == s_.end()) return &quot;&quot;;    
    auto it = m-&gt;second.upper_bound(timestamp);
    if (it == begin(m-&gt;second)) return &quot;&quot;;
    return prev(it)-&gt;second;
  }
private:
  unordered_map&lt;string, map&lt;int, string&gt;&gt; s_; 
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-981-time-based-key-value-store/">花花酱 LeetCode 981. Time Based Key-Value Store</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-981-time-based-key-value-store/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 956. Tallest Billboard</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-956-tallest-billboard/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-956-tallest-billboard/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 10 Dec 2018 01:14:18 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[difference]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[pair]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4423</guid>

					<description><![CDATA[<p>Problem You are installing a billboard and want it to have the largest height.  The billboard will have two steel supports, one on each side. &#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-956-tallest-billboard/">花花酱 LeetCode 956. Tallest Billboard</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/iPRWkifQgoo?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></p>
<p><iframe width="500" height="375" src="https://www.youtube.com/embed/WqLslW2sFxU?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></p>
<h1><strong>Problem</strong></h1>
<p>You are installing a billboard and want it to have the largest height.  The billboard will have two steel supports, one on each side.  Each steel support must be an equal height.</p>
<p>You have a collection of <code>rods</code> which can be welded together.  For example, if you have rods of lengths 1, 2, and 3, you can weld them together to make a support of length 6.</p>
<p>Return the largest possible height of your billboard installation.  If you cannot support the billboard, return 0.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-1-1">[1,2,3,6]</span>
<strong>Output: </strong><span id="example-output-1">6</span>
<strong>Explanation:</strong> We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.
</pre>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-2-1">[1,2,3,4,5,6]</span>
<strong>Output: </strong><span id="example-output-2">10</span>
<strong>Explanation:</strong> We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.
</pre>
<p><strong>Example 3:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-3-1">[1,2]</span>
<strong>Output: </strong><span id="example-output-3">0</span>
<strong>Explanation: </strong>The billboard cannot be supported, so we return 0.
</pre>
<p><strong>Note:</strong></p>
<ol>
<li><code>0 &lt;= rods.length &lt;= 20</code></li>
<li><code>1 &lt;= rods[i] &lt;= 1000</code></li>
<li><code>The sum of rods is at most 5000.</code></li>
</ol>
<h1><strong>Solution: DP</strong></h1>
<p>如果直接<strong>暴力搜索</strong>的话时间复杂度是O(3^N)，铁定超时。对于每一根我们可以选择1、放到左边，2、放到右边，3、不使用。最后再看一下左边和右边是否相同。</p>
<p>题目的数据规模中的这句话非常重要：</p>
<p><code>The sum of rods is at most 5000.</code></p>
<p>这句话就是告诉你算法的时间复杂度和sum of rods有关系，通常需要使用DP。</p>
<p>由于每根柱子只能使用一次（让我们想到了 回复 <strong>01背包</strong>），但是我们怎么去描述放到左边还是放到右边呢？</p>
<p>Naive的方法是用 dp[i] 表示使用前i个柱子能够构成的柱子高度的集合。</p>
<p>e.g. dp[i] = {(h1, h2)},  h1 &lt;= h2</p>
<p>和暴力搜索比起来DP已经对状态进行了压缩，因为我并不需要关心h1, h2是通过哪些（在我之前的）柱子构成了，我只关心它们的当前高度。</p>
<p>然后我可以选择</p>
<p>1、不用第i根柱子</p>
<p>2、放到低的那一堆</p>
<p>3、放到高的那一堆</p>
<p>状态转移的伪代码：</p>
<p>for h1, h2 in dp[i &#8211; 1]:</p>
<p>dp[i] += (h1, h2)        # not used</p>
<p>dp[i] += (h1, h2 + h)  # put on higher</p>
<p>if h1 + h &lt; h2:</p>
<p>dp[i] += (h1 + h, h2)  # put on lower</p>
<p>else:</p>
<p>dp[i] += (h2, h1 + h)  # put on lower</p>
<p>假设 rods=[1,1,2]</p>
<p>dp[0] = {(0,0)}</p>
<p>dp[1] = {(0,0), (0,1)}</p>
<p>dp[2] = {(0,0), (0,1), (0,2), <strong>(1,1)</strong>}</p>
<p>dp[3] = {(0,0), (0,1), (0,2), (0,3), (0,4), (1,1), (1,2), (1,3), <strong>(2,2)</strong>}</p>
<p>但是dp[i]这个集合的大小可能达到sum^2，所以还是会超时&#8230;</p>
<p>时间复杂度 O(n*sum^2)</p>
<p>空间复杂度 O(n*sum^2) 可降维至 O(sum^2)</p>
<p>革命尚未成功，同志仍需努力!</p>
<p>all pairs的cost太大，我们还需要继续压缩状态！</p>
<p><strong>重点来了</strong></p>
<p>通过观察发现，若有2个pairs：</p>
<p>(h1, h2), (h3, h4),</p>
<p>h1 &lt;= h2, h3 &lt;= h4, h1 &lt; h3, h2 &#8211; h1 = h4 &#8211; h3 即 <strong>高度差</strong> 相同</p>
<p>如果 min(h1, h2) &lt; min(h3, h4) 那么(h1, h2) 不可能产生最优解，直接舍弃。</p>
<p>因为如果后面的柱子可以构成 h4 &#8211; h3/h2 &#8211; h1 填补高度差，使得两根柱子一样高，那么答案就是 h2 和 h4。但h2 &lt; h4，所以最优解只能来自后者。</p>
<p>举个例子：我有 (1, 3) 和 (2, 4) 两个pairs，它们的高度差都是2，假设我还有一个长度为2的柱子，那么我可以构成(1+2, 3) 以及 (2+2, 4)，虽然这两个都是解。但是后者的高度要大于前者，所以前者无法构成最优解，也就没必要存下来。</p>
<p>所以，我们可以把<strong>状态压缩到高度差</strong>，<strong>对于相同的高度差，我只存h1最大的</strong>。</p>
<p>我们用 dp[i][j] 来表示使用前i个柱子，高度差为j的情况下最大的公共高度h1是多少。</p>
<p>状态转移（如下图）</p>
<p>dp[i][j] = max(dp[i][j], dp[i &#8211; 1][j])</p>
<p>dp[i][j+h] = max(dp[i][j + h], dp[i &#8211; 1][j])</p>
<p>dp[i][|j-h|] = max(dp[i][|j-h|], dp[i &#8211; 1][j] + min(j, h))</p>
<p>时间复杂度 O(nsum)</p>
<p>空间复杂度 O(nsum) 可降维至 O(sum)</p>
<p><img class="alignnone size-full wp-image-4428" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/956-ep234.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/956-ep234.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/956-ep234-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/956-ep234-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p><img class="alignnone size-full wp-image-4432" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/956-ep234-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/956-ep234-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/956-ep234-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/956-ep234-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p>dp[i] := max common height of two piles of height difference i.</p>
<p>e.g. y1 = 5, y2 = 9 =&gt; dp[9 &#8211; 5] = min(5, 9) =&gt; dp[4] = 5.</p>
<p>answer: dp[0]</p>
<p>Time complexity: O(n*Sum)</p>
<p>Space complexity: O(Sum)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++ hashmap</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua, 172 ms
class Solution {
public:
  int tallestBillboard(vector&lt;int&gt;&amp; rods) {
    unordered_map&lt;int, int&gt; dp;
    dp[0] = 0;
    for (int rod : rods) {      
      auto cur = dp;
      for (const auto&amp; kv : cur) {
        const int k = kv.first;
        dp[k + rod] = max(dp[k + rod], cur[k]);
        dp[abs(k - rod)] = max(dp[abs(k - rod)], cur[k] + min(rod, k));
      }    
    }
    return dp[0];
  }
};</pre><p></div><h2 class="tabtitle">C++ / array</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua, 8 ms
class Solution {
public:
  int tallestBillboard(vector&lt;int&gt;&amp; rods) {    
    const int s = accumulate(begin(rods), end(rods), 0);
    vector&lt;int&gt; dp(s + 1, -1);    
    dp[0] = 0;
    for (int rod : rods) {    
      vector&lt;int&gt; cur(dp);
      for (int i = 0; i &lt;= s - rod; ++i) {
        if (cur[i] &lt; 0) continue;
        dp[i + rod] = max(dp[i + rod], cur[i]);
        dp[abs(i - rod)] = max(dp[abs(i - rod)], cur[i] + min(rod, i));
      }    
    }
    return dp[0];
  }
};</pre><p></div><h2 class="tabtitle">C++/2D array</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua, 12 ms
class Solution {
public:
  int tallestBillboard(vector&lt;int&gt;&amp; rods) {    
    const int n = rods.size();
    const int s = accumulate(begin(rods), end(rods), 0);
    // dp[i][j] := min(h1, h2), j = abs(h1 - h2)
    vector&lt;vector&lt;int&gt;&gt; dp(n + 1, vector&lt;int&gt;(s + 1, -1));
    dp[0][0] = 0;
    for (int i = 1; i &lt;= n; ++i) {      
      int h = rods[i - 1];
      for (int j = 0; j &lt;= s - h; ++j) {
        if (dp[i - 1][j] &lt; 0) continue;
        // not used
        dp[i][j] = max(dp[i][j], dp[i - 1][j]);  
        // put on the taller one 
        dp[i][j + h] = max(dp[i][j + h], dp[i - 1][j]); 
        // put on the shorter one
        dp[i][abs(j - h)] = max(dp[i][abs(j - h)], dp[i - 1][j] + min(h, j)); 
      }    
    }
    return dp[n][0];
  }
};</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-956-tallest-billboard/">花花酱 LeetCode 956. Tallest Billboard</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-956-tallest-billboard/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1. Two Sum</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-1-two-sum/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-1-two-sum/#comments</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 23 Nov 2017 08:14:13 +0000</pubDate>
				<category><![CDATA[Easy]]></category>
		<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[pair]]></category>
		<category><![CDATA[sum]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=903</guid>

					<description><![CDATA[<p>Problem: Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1-two-sum/">花花酱 LeetCode 1. Two Sum</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="281" src="https://www.youtube.com/embed/tNtk_rwbaIk?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p><strong>Problem:</strong></p>
<p>Given an array of integers, return <b>indices</b> of the two numbers such that they add up to a specific target.</p>
<p>You may assume that each input would have <b><i>exactly</i></b> one solution, and you may not use the <i>same</i> element twice.</p>
<p><b>Example:</b></p>
<pre class="crayon:false">Given nums = [2, 7, 11, 15], target = 9,

Because nums[<b>0</b>] + nums[<b>1</b>] = 2 + 7 = 9,
return [<b>0</b>, <b>1</b>].</pre>
<p><strong>Idea:</strong></p>
<p>Brute force / Hashtable</p>
<p><strong>Solution1:</strong></p>
<p>Brute force / C++</p>
<p>Time complexity: O(n^2)</p>
<p>Space complexity: O(1)</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 166 ms
class Solution {
public:
  vector&lt;int&gt; twoSum(vector&lt;int&gt;&amp; nums, int target) {
    for (int i = 0; i &lt; nums.size(); ++i) {
      for (int j = i + 1;j &lt; nums.size(); ++j) {
        int sum = nums[i] + nums[j];
        if (sum == target) {
          return {i, j};
        }
      }
    }
    return {};
  }
};</pre><p><strong>Solution 2:</strong></p>
<p>Hashtable / C++</p>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(n)</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 6 ms
class Solution {
public:
  vector&lt;int&gt; twoSum(vector&lt;int&gt;&amp; nums, int target) {
    unordered_map&lt;int, int&gt; indies;
    for (int i = 0; i &lt; nums.size(); ++i)
      indies[nums[i]] = i;
    
    for (int i = 0; i &lt; nums.size(); ++i) {
      int left = target - nums[i];
      if (indies.count(left) &amp;&amp; indies[left] != i) {
          return {i, indies[left]};
      }
    }
    return {};
  }
};</pre><p>&nbsp;</p>
<p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1-two-sum/">花花酱 LeetCode 1. Two Sum</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-1-two-sum/feed/</wfw:commentRss>
			<slash:comments>2</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>
	</channel>
</rss>
