<?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>sort &#8211; Huahua&#8217;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/sort/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog</link>
	<description></description>
	<lastBuildDate>Thu, 17 Apr 2025 03:28:51 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.2</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>sort &#8211; Huahua&#8217;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 3517. Smallest Palindromic Rearrangement I</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-3517-smallest-palindromic-rearrangement-i/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-3517-smallest-palindromic-rearrangement-i/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 17 Apr 2025 03:19:33 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[Palindrome]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10364</guid>

					<description><![CDATA[这题考查的是排序吧&#8230; 还有rbegin的使用。 普通排序：时间 O(nlogn) / 空间 O(1) 前半部分顺序排序，后半部分逆序排序。 [crayon-6800b8cce304b424896019/] 计数排序：时间：O(n)，空间：O(n) -> O(1) 首尾一起写 [crayon-6800b8cce3060801946253/]]]></description>
										<content:encoded><![CDATA[
<p>这题考查的是排序吧&#8230; 还有rbegin的使用。</p>



<p>普通排序：时间 O(nlogn) / 空间 O(1)</p>



<p>前半部分顺序排序，后半部分逆序排序。</p>



<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  string smallestPalindrome(string s) {
    const int n = s.length();
    sort(begin(s), begin(s) + n / 2);
    sort(rbegin(s), rbegin(s) + n / 2);
    return s;
  }
};</pre>



<p>计数排序：时间：O(n)，空间：O(n) -> O(1)</p>



<p>首尾一起写</p>



<pre class="urvanov-syntax-highlighter-plain-tag">// 7 ms, 54.65MB
class Solution {
public:
  string smallestPalindrome(string s) {
    vector&lt;int&gt; f(128);
    for (size_t i = 0; i &lt; s.size() / 2; ++i)
      ++f[s[i]];
    auto h=begin(s);
    auto t=rbegin(s);
    for (char c = 'a'; c &lt;= 'z'; ++c)
      while (f[c]--)
        *h++ = *t++ = c;
    return s;
  }
};</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-3517-smallest-palindromic-rearrangement-i/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 368. Largest Divisible Subset</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-368-largest-divisible-subset/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-368-largest-divisible-subset/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 05 Apr 2025 02:17:49 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[subset]]></category>
		<category><![CDATA[unique]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10266</guid>

					<description><![CDATA[也算是一道比较经典的DP题了，需要找到一个最大的子集，使得其中元素两两的余数为0。 我们假设有一个集合为{a1, a2, a3, &#8230;, an}, {a1 &#60; a2 &#60; &#8230; &#60; an) 如果 a2 % a1 = 0, a3 % a2 == 0, 那么a3&#8230;]]></description>
										<content:encoded><![CDATA[
<p>也算是一道比较经典的DP题了，需要找到一个最大的子集，使得其中元素两两的余数为0。</p>



<p>我们假设有一个集合为{a1, a2, a3, &#8230;, an}, {a1 &lt; a2 &lt; &#8230; &lt; an)</p>



<p>如果 a2 % a1 = 0,  a3 % a2 == 0, 那么a3 % a1 一定也等于0。也就是说a2是a1的倍数，a3是a2的倍数，那么a3一定也是a1的倍数。所以我们并不需要测试任意两个元素之间的余数为0，我们只需要检测a[i]是否为a[i-1]的倍数即可，如果成立，则可以确保a[i]也是a[i-2], a[i-3], &#8230; a[1]的倍数。这样就可以大大降低问题的复杂度。</p>



<p>接下来就需要dp就发挥威力了。我们将原数组排序，用dp[i]来表示以a[i]结尾（集合中的最大值），能够构建的子集的最大长度。</p>



<p>转移方程：dp[j] = max(dp[j], dp[i] + 1) if nums[j] % nums[i] = 0.</p>



<p>这表示，如果nums[j] 是 nums[i]的倍数，那么我们可以把nums[j]加入以nums[i]结尾的最大子集中，构建一个新的最大子集，长度+1。当然对于j，可能有好多个满足条件的i，我们需要找一个最大的。</p>



<p>举个例子：<br>nums = {2, 3, 4, 12}<br>以3结尾的最大子集{3}，长度为1。由于12%3==0，那么我们可以把12追加到{3} 中，构成{3,12}。<br>以4结尾的最大子集是{2,4}，长度为2。由于12%4==0，那么我们可以把12追加到{2,4} 中，构成{2,4,12} 。得到最优解。</p>



<p>这样我们只需要双重循环，枚举i，再枚举j (0 &lt;= i &lt; j)。时间复杂度：O(n^2)。空间复杂度：O(n)。</p>



<p>最后需要输出一个最大子集，如果不记录递推过程，则需要稍微判断一下。</p>



<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  vector&lt;int&gt; largestDivisibleSubset(vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();
    sort(begin(nums), end(nums));
    // dp[i] = max size of subset ends with nums[i]
    vector&lt;int&gt; dp(n);
    for (int i = 0; i &lt; n; ++i)
      for (int j = i + 1; j &lt; n; ++j)
        if (nums[j] % nums[i] == 0)
          dp[j] = max(dp[j], dp[i] + 1);
    int s = *max_element(begin(dp), end(dp));
    vector&lt;int&gt; ans;
    for (int i = n - 1; i &gt;= 0; --i) {
      if (dp[i] == s &amp;&amp; (ans.empty() || ans.back() % nums[i] == 0)) {
        ans.push_back(nums[i]);
        --s;
      }
    }
    return ans;
  }
};</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-368-largest-divisible-subset/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 3462. Maximum Sum With at Most K Elements</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-3462-maximum-sum-with-at-most-k-elements/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-3462-maximum-sum-with-at-most-k-elements/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 28 Mar 2025 04:24:17 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[fast parition]]></category>
		<category><![CDATA[partial sorting]]></category>
		<category><![CDATA[sort]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10232</guid>

					<description><![CDATA[本题使用了两次 partial sorting / std::nth_element 来进行部分排序，可以作为经典教程了。 速度比全排序或者heap/pq快到不知道哪里去了～ Time complexity: O(m*n)Space complexity: O(m*n) 不用黑科技就达到99.77% [crayon-6800b8cce3e82898923368/]]]></description>
										<content:encoded><![CDATA[
<p>本题使用了两次 partial sorting / std::nth_element 来进行部分排序，可以作为经典教程了。</p>



<p>速度比全排序或者heap/pq快到不知道哪里去了～</p>



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



<p>不用黑科技就达到99.77%</p>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2025/03/Screenshot-2025-03-27-at-9.19.52 PM.png"><img fetchpriority="high" decoding="async" width="815" height="448" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2025/03/Screenshot-2025-03-27-at-9.19.52 PM.png" alt="" class="wp-image-10233" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2025/03/Screenshot-2025-03-27-at-9.19.52 PM.png 815w, https://zxi.mytechroad.com/blog/wp-content/uploads/2025/03/Screenshot-2025-03-27-at-9.19.52 PM-300x165.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2025/03/Screenshot-2025-03-27-at-9.19.52 PM-768x422.png 768w" sizes="(max-width: 815px) 100vw, 815px" /></a></figure>



<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  long long maxSum(vector&lt;vector&lt;int&gt;&gt;&amp; grid, vector&lt;int&gt;&amp; limits, int k) {
    // Step 1: Sort each row using fast parition, collect largest limits[i] elements.
    vector&lt;int&gt; nums;
    nums.reserve(grid.size() * grid[0].size());
    for (int i = 0; i &lt; grid.size(); ++i) {
      nth_element(begin(grid[i]), begin(grid[i]) + limits[i], end(grid[i]), std::greater{});
      nums.insert(nums.end(), begin(grid[i]), begin(grid[i]) + limits[i]);
    }

    // Setp 2: fast partition to find the largest k elements. O(m*n).
    nth_element(begin(nums), begin(nums) + k, end(nums), std::greater{});
    
    // Step 3: Sum them up. O(k)
    return accumulate(begin(nums), begin(nums) + k, 0LL);
  }
};</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-3462-maximum-sum-with-at-most-k-elements/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2441. Largest Positive Integer That Exists With Its Negative</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-2441-largest-positive-integer-that-exists-with-its-negative%ef%bf%bc%ef%bf%bc/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-2441-largest-positive-integer-that-exists-with-its-negative%ef%bf%bc%ef%bf%bc/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 16 Oct 2022 04:56:53 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[abs]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[sort]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9866</guid>

					<description><![CDATA[Given an integer array&#160;nums&#160;that&#160;does not contain&#160;any zeros, find&#160;the largest positive&#160;integer&#160;k&#160;such that&#160;-k&#160;also exists in the array. Return&#160;the positive integer&#160;k. If there is no such integer, return&#160;-1.&#8230;]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 2441. Largest Positive Integer That Exists With Its Negative - 刷题找工作 EP404" width="500" height="281" src="https://www.youtube.com/embed/HItywpd0-yY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>Given an integer array&nbsp;<code>nums</code>&nbsp;that&nbsp;<strong>does not contain</strong>&nbsp;any zeros, find&nbsp;<strong>the largest positive</strong>&nbsp;integer&nbsp;<code>k</code>&nbsp;such that&nbsp;<code>-k</code>&nbsp;also exists in the array.</p>



<p>Return&nbsp;<em>the positive integer&nbsp;</em><code>k</code>. If there is no such integer, return&nbsp;<code>-1</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [-1,2,-3,3]
<strong>Output:</strong> 3
<strong>Explanation:</strong> 3 is the only valid k we can find in the array.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [-1,10,6,7,-7,1]
<strong>Output:</strong> 7
<strong>Explanation:</strong> Both 1 and 7 have their corresponding negative values in the array. 7 has a larger value.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [-10,8,6,7,-2,-3]
<strong>Output:</strong> -1
<strong>Explanation:</strong> There is no a single valid k, we return -1.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= nums.length &lt;= 1000</code></li><li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li><li><code>nums[i] != 0</code></li></ul>



<h2 class="wp-block-heading"><strong>Solution 1: Hashtable</strong></h2>



<p>We can do in one pass by checking whether -x in the hashtable and update ans with abs(x) if so.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int findMaxK(vector&lt;int&gt;&amp; nums) {
    unordered_set&lt;int&gt; s;
    int ans = -1;
    for (int x : nums) {
      if (abs(x) &gt; ans &amp;&amp; s.count(-x))
        ans = abs(x);
      s.insert(x);
    }
    return ans;
  }
};</pre>
</div></div>



<h2 class="wp-block-heading"><strong>Solution 2: Sorting</strong></h2>



<p>Sort the array by abs(x) in descending order.</p>



<p>[-1,10,6,7,-7,1] becomes = [-1, 1, 6, -7, 7, 10]</p>



<p>Check whether arr[i] = -arr[i-1].</p>



<p>Time complexity: O(nlogn)<br>Space complexity: O(1)</p>



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int findMaxK(vector&lt;int&gt;&amp; nums) {
    sort(begin(nums), end(nums), [](int a, int b){
      return abs(a) == abs(b) ? a &lt; b : abs(a) &gt; abs(b);
    });    
    for (int i = 1; i &lt; nums.size(); ++i)
      if (nums[i] == -nums[i - 1]) return nums[i];
    return -1;
  }
};</pre>
</div></div>



<h2 class="wp-block-heading"><strong>Solution 3: Two Pointers</strong></h2>



<p>Sort the array.</p>



<p>Let sum = nums[i] + nums[j], sum == 0, we find one pair, if sum &lt; 0, ++i else &#8211;j.</p>



<p>Time complexity: O(nlogn)<br>Space complexity: O(1)</p>



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int findMaxK(vector&lt;int&gt;&amp; nums) {
    sort(begin(nums), end(nums));
    int ans = -1;
    for (int i = 0, j = nums.size() - 1; i &lt; j; ) {
      const int s = nums[i] + nums[j];
      if (s == 0) {
        ans = max(ans, nums[j]);
        ++i, --j;      
      } else if (s &lt; 0) {
        ++i;
      } else {
        --j;
      }      
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-2441-largest-positive-integer-that-exists-with-its-negative%ef%bf%bc%ef%bf%bc/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2418. Sort the People</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2418-sort-the-people/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2418-sort-the-people/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 26 Sep 2022 16:57:17 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[zip]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9842</guid>

					<description><![CDATA[You are given an array of strings&#160;names, and an array&#160;heights&#160;that consists of&#160;distinct&#160;positive integers. Both arrays are of length&#160;n. For each index&#160;i,&#160;names[i]&#160;and&#160;heights[i]&#160;denote the name and height&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given an array of strings&nbsp;<code>names</code>, and an array&nbsp;<code>heights</code>&nbsp;that consists of&nbsp;<strong>distinct</strong>&nbsp;positive integers. Both arrays are of length&nbsp;<code>n</code>.</p>



<p>For each index&nbsp;<code>i</code>,&nbsp;<code>names[i]</code>&nbsp;and&nbsp;<code>heights[i]</code>&nbsp;denote the name and height of the&nbsp;<code>i<sup>th</sup></code>&nbsp;person.</p>



<p>Return&nbsp;<code>names</code><em>&nbsp;sorted in&nbsp;<strong>descending</strong>&nbsp;order by the people&#8217;s heights</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> names = ["Mary","John","Emma"], heights = [180,165,170]
<strong>Output:</strong> ["Mary","Emma","John"]
<strong>Explanation:</strong> Mary is the tallest, followed by Emma and John.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> names = ["Alice","Bob","Bob"], heights = [155,185,150]
<strong>Output:</strong> ["Bob","Alice","Bob"]
<strong>Explanation:</strong> The first Bob is the tallest, followed by Alice and the second Bob.
</pre>



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



<ul class="wp-block-list"><li><code>n == names.length == heights.length</code></li><li><code>1 &lt;= n &lt;= 10<sup>3</sup></code></li><li><code>1 &lt;= names[i].length &lt;= 20</code></li><li><code>1 &lt;= heights[i] &lt;= 10<sup>5</sup></code></li><li><code>names[i]</code>&nbsp;consists of lower and upper case English letters.</li><li>All the values of&nbsp;<code>heights</code>&nbsp;are distinct.</li></ul>



<p>Solution: Zip and sort</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;string&gt; sortPeople(vector&lt;string&gt;&amp; names, vector&lt;int&gt;&amp; heights) {
    vector&lt;pair&lt;int, string*&gt;&gt; data;
    for (int i = 0; i &lt; names.size(); ++i)
      data.emplace_back(heights[i], &amp;names[i]);    
    sort(rbegin(data), rend(data));
    vector&lt;string&gt; ans(names.size());
    for (int i = 0; i &lt; names.size(); ++i)
      ans[i].swap(*data[i].second);
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2418-sort-the-people/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2410. Maximum Matching of Players With Trainers</title>
		<link>https://zxi.mytechroad.com/blog/two-pointers/leetcode-2410-maximum-matching-of-players-with-trainers/</link>
					<comments>https://zxi.mytechroad.com/blog/two-pointers/leetcode-2410-maximum-matching-of-players-with-trainers/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 17 Sep 2022 20:04:24 +0000</pubDate>
				<category><![CDATA[Two pointers]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[two pointers]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9827</guid>

					<description><![CDATA[You are given a&#160;0-indexed&#160;integer array&#160;players, where&#160;players[i]&#160;represents the&#160;ability&#160;of the&#160;ith&#160;player. You are also given a&#160;0-indexed&#160;integer array&#160;trainers, where&#160;trainers[j]&#160;represents the&#160;training capacity&#160;of the&#160;jth&#160;trainer. The&#160;ith&#160;player can&#160;match&#160;with the&#160;jth&#160;trainer if the player&#8217;s ability&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>players</code>, where&nbsp;<code>players[i]</code>&nbsp;represents the&nbsp;<strong>ability</strong>&nbsp;of the&nbsp;<code>i<sup>th</sup></code>&nbsp;player. You are also given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>trainers</code>, where&nbsp;<code>trainers[j]</code>&nbsp;represents the&nbsp;<strong>training capacity&nbsp;</strong>of the&nbsp;<code>j<sup>th</sup></code>&nbsp;trainer.</p>



<p>The&nbsp;<code>i<sup>th</sup></code>&nbsp;player can&nbsp;<strong>match</strong>&nbsp;with the&nbsp;<code>j<sup>th</sup></code>&nbsp;trainer if the player&#8217;s ability is&nbsp;<strong>less than or equal to</strong>&nbsp;the trainer&#8217;s training capacity. Additionally, the&nbsp;<code>i<sup>th</sup></code>&nbsp;player can be matched with at most one trainer, and the&nbsp;<code>j<sup>th</sup></code>&nbsp;trainer can be matched with at most one player.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>maximum</strong>&nbsp;number of matchings between&nbsp;</em><code>players</code><em>&nbsp;and&nbsp;</em><code>trainers</code><em>&nbsp;that satisfy these conditions.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> players = [4,7,9], trainers = [8,2,5,8]
<strong>Output:</strong> 2
<strong>Explanation:</strong>
One of the ways we can form two matchings is as follows:
- players[0] can be matched with trainers[0] since 4 &lt;= 8.
- players[1] can be matched with trainers[3] since 7 &lt;= 8.
It can be proven that 2 is the maximum number of matchings that can be formed.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> players = [1,1,1], trainers = [10]
<strong>Output:</strong> 1
<strong>Explanation:</strong>
The trainer can be matched with any of the 3 players.
Each player can only be matched with one trainer, so the maximum answer is 1.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= players.length, trainers.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= players[i], trainers[j] &lt;= 10<sup>9</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Sort + Two Pointers</strong></h2>



<p>Sort players and trainers.</p>



<p>Loop through players, skip trainers until he/she can match the current players.</p>



<p>Time complexity: O(nlogn + mlogm + n + m)<br>Space complexity: O(1)</p>



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int matchPlayersAndTrainers(vector&lt;int&gt;&amp; players, vector&lt;int&gt;&amp; trainers) {
    sort(begin(players), end(players));
    sort(begin(trainers), end(trainers));
    const int n = players.size();
    const int m = trainers.size();
    int ans = 0;
    for (int i = 0, j = 0; i &lt; n &amp;&amp; j &lt; m; ++i) {
      while (j &lt; m &amp;&amp; players[i] &gt; trainers[j]) ++j;
      if (j++ == m) break;
      ++ans;
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/two-pointers/leetcode-2410-maximum-matching-of-players-with-trainers/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2126. Destroying Asteroids</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-2126-destroying-asteroids/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-2126-destroying-asteroids/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 02 Jan 2022 08:49:30 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[sort]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9401</guid>

					<description><![CDATA[You are given an integer&#160;mass, which represents the original mass of a planet. You are further given an integer array&#160;asteroids, where&#160;asteroids[i]&#160;is the mass of the&#160;ith&#160;asteroid.&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given an integer&nbsp;<code>mass</code>, which represents the original mass of a planet. You are further given an integer array&nbsp;<code>asteroids</code>, where&nbsp;<code>asteroids[i]</code>&nbsp;is the mass of the&nbsp;<code>i<sup>th</sup></code>&nbsp;asteroid.</p>



<p>You can arrange for the planet to collide with the asteroids in&nbsp;<strong>any arbitrary order</strong>. If the mass of the planet is&nbsp;<strong>greater than or equal to</strong>&nbsp;the mass of the asteroid, the asteroid is&nbsp;<strong>destroyed</strong>&nbsp;and the planet&nbsp;<strong>gains</strong>&nbsp;the mass of the asteroid. Otherwise, the planet is destroyed.</p>



<p>Return&nbsp;<code>true</code><em>&nbsp;if&nbsp;<strong>all</strong>&nbsp;asteroids can be destroyed. Otherwise, return&nbsp;</em><code>false</code><em>.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> mass = 10, asteroids = [3,9,19,5,21]
<strong>Output:</strong> true
<strong>Explanation:</strong> One way to order the asteroids is [9,19,5,3,21]:
- The planet collides with the asteroid with a mass of 9. New planet mass: 10 + 9 = 19
- The planet collides with the asteroid with a mass of 19. New planet mass: 19 + 19 = 38
- The planet collides with the asteroid with a mass of 5. New planet mass: 38 + 5 = 43
- The planet collides with the asteroid with a mass of 3. New planet mass: 43 + 3 = 46
- The planet collides with the asteroid with a mass of 21. New planet mass: 46 + 21 = 67
All asteroids are destroyed.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> mass = 5, asteroids = [4,9,23,4]
<strong>Output:</strong> false
<strong>Explanation:</strong> 
The planet cannot ever gain enough mass to destroy the asteroid with a mass of 23.
After the planet destroys the other asteroids, it will have a mass of 5 + 4 + 9 + 4 = 22.
This is less than 23, so a collision would not destroy the last asteroid.</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= mass &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= asteroids.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= asteroids[i] &lt;= 10<sup>5</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Greedy</strong></h2>



<p>Sort asteroids by weight. Note, mass can be very big (<span style="background-color: rgb(243, 243, 243); font-family: monospace; font-size: inherit;">10</span><sup style="font-family: monospace;">5</sup>*<meta charset="utf-8"><span style="background-color: rgb(243, 243, 243); font-family: monospace; font-size: inherit;">10</span><sup style="font-family: monospace;">5</sup>), for C++/Java, use long instead of int.</p>



<p>Time complexity: O(nlogn)<br>Space complexity: O(1)</p>



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  bool asteroidsDestroyed(int mass, vector&lt;int&gt;&amp; asteroids) {
    long long curr = mass;
    sort(begin(asteroids), end(asteroids));
    for (int a : asteroids) {
      if (curr &lt; a) return false;
      curr += a;
    }
    return true;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/greedy/leetcode-2126-destroying-asteroids/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1985. Find the Kth Largest Integer in the Array</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1985-find-the-kth-largest-integer-in-the-array/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1985-find-the-kth-largest-integer-in-the-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 01 Jan 2022 00:11:48 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[nth_element]]></category>
		<category><![CDATA[quick selection]]></category>
		<category><![CDATA[sort]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9367</guid>

					<description><![CDATA[You are given an array of strings&#160;nums&#160;and an integer&#160;k. Each string in&#160;nums&#160;represents an integer without leading zeros. Return&#160;the string that represents the&#160;kth&#160;largest integer&#160;in&#160;nums. Note: Duplicate&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given an array of strings&nbsp;<code>nums</code>&nbsp;and an integer&nbsp;<code>k</code>. Each string in&nbsp;<code>nums</code>&nbsp;represents an integer without leading zeros.</p>



<p>Return&nbsp;<em>the string that represents the&nbsp;</em><code>k<sup>th</sup></code><em><strong>&nbsp;largest integer</strong>&nbsp;in&nbsp;</em><code>nums</code>.</p>



<p><strong>Note</strong>: Duplicate numbers should be counted distinctly. For example, if&nbsp;<code>nums</code>&nbsp;is&nbsp;<code>["1","2","2"]</code>,&nbsp;<code>"2"</code>&nbsp;is the first largest integer,&nbsp;<code>"2"</code>&nbsp;is the second-largest integer, and&nbsp;<code>"1"</code>&nbsp;is the third-largest integer.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = ["3","6","7","10"], k = 4
<strong>Output:</strong> "3"
<strong>Explanation:</strong>
The numbers in nums sorted in non-decreasing order are ["3","6","7","10"].
The 4<sup>th</sup> largest integer in nums is "3".
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = ["2","21","12","1"], k = 3
<strong>Output:</strong> "2"
<strong>Explanation:</strong>
The numbers in nums sorted in non-decreasing order are ["1","2","12","21"].
The 3<sup>rd</sup> largest integer in nums is "2".
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = ["0","0"], k = 2
<strong>Output:</strong> "0"
<strong>Explanation:</strong>
The numbers in nums sorted in non-decreasing order are ["0","0"].
The 2<sup>nd</sup> largest integer in nums is "0".
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= k &lt;= nums.length &lt;= 10<sup>4</sup></code></li><li><code>1 &lt;= nums[i].length &lt;= 100</code></li><li><code>nums[i]</code>&nbsp;consists of only digits.</li><li><code>nums[i]</code>&nbsp;will not have any leading zeros.</li></ul>



<h2 class="wp-block-heading"><strong>Solution: nth_element / quick selection</strong></h2>



<p>Use <a rel="noreferrer noopener" href="https://en.cppreference.com/w/cpp/algorithm/nth_element" target="_blank">std::nth_element</a> to find the k-th largest element. When comparing two strings, compare their lengths first and compare their content if they have the same length.</p>



<p>Time complexity: O(n) on average<br>Space complexity: O(1)</p>



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  string kthLargestNumber(vector&lt;string&gt;&amp; nums, int k) {    
    nth_element(begin(nums), begin(nums) + k - 1, end(nums), [](const auto&amp; a, const auto&amp; b) {
      return a.length() == b.length() ? a &gt; b : a.length() &gt; b.length();      
    });
    return nums[k - 1];
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1985-find-the-kth-largest-integer-in-the-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1984. Minimum Difference Between Highest and Lowest of K Scores</title>
		<link>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1984-minimum-difference-between-highest-and-lowest-of-k-scores/</link>
					<comments>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1984-minimum-difference-between-highest-and-lowest-of-k-scores/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 31 Dec 2021 23:59:40 +0000</pubDate>
				<category><![CDATA[Sliding Window]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[sliding window]]></category>
		<category><![CDATA[sort]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9363</guid>

					<description><![CDATA[You are given a&#160;0-indexed&#160;integer array&#160;nums, where&#160;nums[i]&#160;represents the score of the&#160;ith&#160;student. You are also given an integer&#160;k. Pick the scores of any&#160;k&#160;students from the array so&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>nums</code>, where&nbsp;<code>nums[i]</code>&nbsp;represents the score of the&nbsp;<code>i<sup>th</sup></code>&nbsp;student. You are also given an integer&nbsp;<code>k</code>.</p>



<p>Pick the scores of any&nbsp;<code>k</code>&nbsp;students from the array so that the&nbsp;<strong>difference</strong>&nbsp;between the&nbsp;<strong>highest</strong>&nbsp;and the&nbsp;<strong>lowest</strong>&nbsp;of the&nbsp;<code>k</code>&nbsp;scores is&nbsp;<strong>minimized</strong>.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>minimum</strong>&nbsp;possible difference</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [90], k = 1
<strong>Output:</strong> 0
<strong>Explanation:</strong> There is one way to pick score(s) of one student:
- [<strong><u>90</u></strong>]. The difference between the highest and lowest score is 90 - 90 = 0.
The minimum possible difference is 0.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [9,4,1,7], k = 2
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are six ways to pick score(s) of two students:
- [<strong><u>9</u></strong>,<strong><u>4</u></strong>,1,7]. The difference between the highest and lowest score is 9 - 4 = 5.
- [<strong><u>9</u></strong>,4,<strong><u>1</u></strong>,7]. The difference between the highest and lowest score is 9 - 1 = 8.
- [<strong><u>9</u></strong>,4,1,<strong><u>7</u></strong>]. The difference between the highest and lowest score is 9 - 7 = 2.
- [9,<strong><u>4</u></strong>,<strong><u>1</u></strong>,7]. The difference between the highest and lowest score is 4 - 1 = 3.
- [9,<strong><u>4</u></strong>,1,<strong><u>7</u></strong>]. The difference between the highest and lowest score is 7 - 4 = 3.
- [9,4,<strong><u>1</u></strong>,<strong><u>7</u></strong>]. The difference between the highest and lowest score is 7 - 1 = 6.
The minimum possible difference is 2.</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= k &lt;= nums.length &lt;= 1000</code></li><li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Sliding Window</strong></h2>



<p>Sort the array, to minimize the difference, k numbers must be consecutive (i.e, from a subarray). We use a sliding window size of k and try all possible subarrays. <br>Ans = min{(nums[k &#8211; 1] &#8211; nums[0]), (nums[k] &#8211; nums[1]), &#8230; (nums[n &#8211; 1] &#8211; nums[n &#8211; k])}</p>



<p>Time complexity: O(nlogn)<br>Space complexity: O(1)</p>



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int minimumDifference(vector&lt;int&gt;&amp; nums, int k) {
    int ans = INT_MAX;
    sort(begin(nums), end(nums));
    for (int i = k - 1; i &lt; nums.size(); ++i)
      ans = min(ans, nums[i] - nums[i - k + 1]);
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1984-minimum-difference-between-highest-and-lowest-of-k-scores/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 215. Kth Largest Element in an Array</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-215-kth-largest-element-in-an-array/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-215-kth-largest-element-in-an-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 06 Dec 2021 04:06:14 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[quick select]]></category>
		<category><![CDATA[sort]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9053</guid>

					<description><![CDATA[Given an integer array&#160;nums&#160;and an integer&#160;k, return&#160;the&#160;kth&#160;largest element in the array. Note that it is the&#160;kth&#160;largest element in the sorted order, not the&#160;kth&#160;distinct element. Example&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Given an integer array&nbsp;<code>nums</code>&nbsp;and an integer&nbsp;<code>k</code>, return&nbsp;<em>the</em>&nbsp;<code>k<sup>th</sup></code>&nbsp;<em>largest element in the array</em>.</p>



<p>Note that it is the&nbsp;<code>k<sup>th</sup></code>&nbsp;largest element in the sorted order, not the&nbsp;<code>k<sup>th</sup></code>&nbsp;distinct element.</p>



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



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



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



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



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



<ul class="wp-block-list"><li><code>1 &lt;= k &lt;= nums.length &lt;= 10<sup>4</sup></code></li><li><code>-10<sup>4</sup>&nbsp;&lt;= nums[i] &lt;= 10<sup>4</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Quick selection</strong></h2>



<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="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int findKthLargest(vector&lt;int&gt;&amp; nums, int k) {
    nth_element(nums.begin(), nums.begin() + k - 1, nums.end(), std::greater&lt;int&gt;());
    return nums[k - 1];
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-215-kth-largest-element-in-an-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 147. Insertion Sort List</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-147-insertion-sort-list/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-147-insertion-sort-list/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 29 Nov 2021 06:48:33 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[insertion]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[sort]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8922</guid>

					<description><![CDATA[Given the&#160;head&#160;of a singly linked list, sort the list using&#160;insertion sort, and return&#160;the sorted list&#8217;s head. The steps of the&#160;insertion sort&#160;algorithm: Insertion sort iterates, consuming&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Given the&nbsp;<code>head</code>&nbsp;of a singly linked list, sort the list using&nbsp;<strong>insertion sort</strong>, and return&nbsp;<em>the sorted list&#8217;s head</em>.</p>



<p>The steps of the&nbsp;<strong>insertion sort</strong>&nbsp;algorithm:</p>



<ol class="wp-block-list"><li>Insertion sort iterates, consuming one input element each repetition and growing a sorted output list.</li><li>At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there.</li><li>It repeats until no input elements remain.</li></ol>



<p>The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration.</p>



<figure class="wp-block-image"><img decoding="async" src="https://upload.wikimedia.org/wikipedia/commons/0/0f/Insertion-sort-example-300px.gif" alt=""/></figure>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/03/04/sort1linked-list.jpg" alt=""/></figure>



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



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/03/04/sort2linked-list.jpg" alt=""/></figure>



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



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



<ul class="wp-block-list"><li>The number of nodes in the list is in the range&nbsp;<code>[1, 5000]</code>.</li><li><code>-5000 &lt;= Node.val &lt;= 5000</code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Scan from head</strong></h2>



<p>For each node, scan from head of the list to find the insertion position in O(n), and adjust pointers.</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="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  ListNode* insertionSortList(ListNode* head) {
    ListNode dummy;
    
    while (head) {
      ListNode* iter = &amp;dummy;
      while (iter-&gt;next &amp;&amp; head-&gt;val &gt; iter-&gt;next-&gt;val)
        iter = iter-&gt;next;
      ListNode* next = head-&gt;next;
      head-&gt;next = iter-&gt;next;
      iter-&gt;next = head;
      head = next;
    }
    
    return dummy.next;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/list/leetcode-147-insertion-sort-list/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2054. Two Best Non-Overlapping Events</title>
		<link>https://zxi.mytechroad.com/blog/heap/leetcode-2054-two-best-non-overlapping-events/</link>
					<comments>https://zxi.mytechroad.com/blog/heap/leetcode-2054-two-best-non-overlapping-events/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 02 Nov 2021 02:16:37 +0000</pubDate>
				<category><![CDATA[Heap]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[sort]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8653</guid>

					<description><![CDATA[You are given a&#160;0-indexed&#160;2D integer array of&#160;events&#160;where&#160;events[i] = [startTimei, endTimei, valuei]. The&#160;ith&#160;event starts at&#160;startTimeiand ends at&#160;endTimei, and if you attend this event, you will receive&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;2D integer array of&nbsp;<code>events</code>&nbsp;where&nbsp;<code>events[i] = [startTime<sub>i</sub>, endTime<sub>i</sub>, value<sub>i</sub>]</code>. The&nbsp;<code>i<sup>th</sup></code>&nbsp;event starts at&nbsp;<code>startTime<sub>i</sub></code>and ends at&nbsp;<code>endTime<sub>i</sub></code>, and if you attend this event, you will receive a value of&nbsp;<code>value<sub>i</sub></code>. You can choose&nbsp;<strong>at most</strong>&nbsp;<strong>two</strong>&nbsp;<strong>non-overlapping</strong>&nbsp;events to attend such that the sum of their values is&nbsp;<strong>maximized</strong>.</p>



<p>Return&nbsp;<em>this&nbsp;<strong>maximum</strong>&nbsp;sum.</em></p>



<p>Note that the start time and end time is&nbsp;<strong>inclusive</strong>: that is, you cannot attend two events where one of them starts and the other ends at the same time. More specifically, if you attend an event with end time&nbsp;<code>t</code>, the next event must start at or after&nbsp;<code>t + 1</code>.</p>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/09/21/picture5.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> events = [[1,3,2],[4,5,2],[2,4,3]]
<strong>Output:</strong> 4
<strong>Explanation: </strong>Choose the green events, 0 and 1 for a sum of 2 + 2 = 4.
</pre>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/09/21/picture1.png" alt="Example 1 Diagram"/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> events = [[1,3,2],[4,5,2],[1,5,5]]
<strong>Output:</strong> 5
<strong>Explanation: </strong>Choose event 2 for a sum of 5.
</pre>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/09/21/picture3.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> events = [[1,5,3],[1,5,1],[6,6,5]]
<strong>Output:</strong> 8
<strong>Explanation: </strong>Choose events 0 and 2 for a sum of 3 + 5 = 8.</pre>



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



<ul class="wp-block-list"><li><code>2 &lt;= events.length &lt;= 10<sup>5</sup></code></li><li><code>events[i].length == 3</code></li><li><code>1 &lt;= startTime<sub>i</sub>&nbsp;&lt;= endTime<sub>i</sub>&nbsp;&lt;= 10<sup>9</sup></code></li><li><code>1 &lt;= value<sub>i</sub>&nbsp;&lt;= 10<sup>6</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Sort + Heap</strong></h2>



<p>Sort events by start time, process them from left to right.</p>



<p>Use a min heap to store the events processed so far, a variable cur to track the max value of a non-overlapping event.</p>



<p>For a given event, pop all non-overlapping events whose end time is smaller than its start time and update cur.</p>



<p>ans = max(val + cur)</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int maxTwoEvents(vector&lt;vector&lt;int&gt;&gt;&amp; events) {
    using E = pair&lt;int,int&gt;;
    sort(begin(events), end(events));
    priority_queue&lt;E, vector&lt;E&gt;, greater&lt;E&gt;&gt; q; // (end_time, val)
    int ans = 0;
    int cur = 0;
    for (const auto&amp; e : events) {
      while (!q.empty() &amp;&amp; q.top().first &lt; e[0]) {
        cur = max(cur, q.top().second);
        q.pop();
      }
      ans = max(ans, cur + e[2]);
      q.emplace(e[1], e[2]);
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/heap/leetcode-2054-two-best-non-overlapping-events/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1859. Sorting the Sentence</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-1859-sorting-the-sentence/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-1859-sorting-the-sentence/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 29 May 2021 22:47:12 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[words]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8456</guid>

					<description><![CDATA[A&#160;sentence&#160;is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase&#8230;]]></description>
										<content:encoded><![CDATA[
<p>A&nbsp;<strong>sentence</strong>&nbsp;is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters.</p>



<p>A sentence can be&nbsp;<strong>shuffled</strong>&nbsp;by appending the&nbsp;<strong>1-indexed word position</strong>&nbsp;to each word then rearranging the words in the sentence.</p>



<ul class="wp-block-list"><li>For example, the sentence&nbsp;<code>"This is a sentence"</code>&nbsp;can be shuffled as&nbsp;<code>"sentence4 a3 is2 This1"</code>&nbsp;or&nbsp;<code>"is2 sentence4 This1 a3"</code>.</li></ul>



<p>Given a&nbsp;<strong>shuffled sentence</strong>&nbsp;<code>s</code>&nbsp;containing no more than&nbsp;<code>9</code>&nbsp;words, reconstruct and return&nbsp;<em>the original sentence</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "is2 sentence4 This1 a3"
<strong>Output:</strong> "This is a sentence"
<strong>Explanation:</strong> Sort the words in s to their original positions "This1 is2 a3 sentence4", then remove the numbers.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "Myself2 Me1 I4 and3"
<strong>Output:</strong> "Me Myself and I"
<strong>Explanation:</strong> Sort the words in s to their original positions "Me1 Myself2 and3 I4", then remove the numbers.
</pre>



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



<ul class="wp-block-list"><li><code>2 &lt;= s.length &lt;= 200</code></li><li><code>s</code>&nbsp;consists of lowercase and uppercase English letters, spaces, and digits from&nbsp;<code>1</code>&nbsp;to&nbsp;<code>9</code>.</li><li>The number of words in&nbsp;<code>s</code>&nbsp;is between&nbsp;<code>1</code>&nbsp;and&nbsp;<code>9</code>.</li><li>The words in&nbsp;<code>s</code>&nbsp;are separated by a single space.</li><li><code>s</code>&nbsp;contains no leading or trailing spaces.</li></ul>



<h2 class="wp-block-heading"><strong>Solution: String</strong></h2>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">class Solution:
  def sortSentence(self, s: str) -&gt; str:
    p = [(w[:-1], int(w[-1])) for w in s.split()]
    p.sort(key=lambda x : x[1])
    return &quot; &quot;.join((w for w, _ in p))</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-1859-sorting-the-sentence/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1846. Maximum Element After Decreasing and Rearranging</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1846-maximum-element-after-decreasing-and-rearranging/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1846-maximum-element-after-decreasing-and-rearranging/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 01 May 2021 22:37:29 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[sort]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8414</guid>

					<description><![CDATA[You are given an array of positive integers&#160;arr. Perform some operations (possibly none) on&#160;arr&#160;so that it satisfies these conditions: The value of the&#160;first&#160;element in&#160;arr&#160;must be&#160;1.&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given an array of positive integers&nbsp;<code>arr</code>. Perform some operations (possibly none) on&nbsp;<code>arr</code>&nbsp;so that it satisfies these conditions:</p>



<ul class="wp-block-list"><li>The value of the&nbsp;<strong>first</strong>&nbsp;element in&nbsp;<code>arr</code>&nbsp;must be&nbsp;<code>1</code>.</li><li>The absolute difference between any 2 adjacent elements must be&nbsp;<strong>less than or equal to&nbsp;</strong><code>1</code>. In other words,&nbsp;<code>abs(arr[i] - arr[i - 1]) &lt;= 1</code>&nbsp;for each&nbsp;<code>i</code>&nbsp;where&nbsp;<code>1 &lt;= i &lt; arr.length</code>&nbsp;(<strong>0-indexed</strong>).&nbsp;<code>abs(x)</code>&nbsp;is the absolute value of&nbsp;<code>x</code>.</li></ul>



<p>There are 2 types of operations that you can perform any number of times:</p>



<ul class="wp-block-list"><li><strong>Decrease</strong>&nbsp;the value of any element of&nbsp;<code>arr</code>&nbsp;to a&nbsp;<strong>smaller positive integer</strong>.</li><li><strong>Rearrange</strong>&nbsp;the elements of&nbsp;<code>arr</code>&nbsp;to be in any order.</li></ul>



<p>Return&nbsp;<em>the&nbsp;<strong>maximum</strong>&nbsp;possible value of an element in&nbsp;</em><code>arr</code><em>&nbsp;after performing the operations to satisfy the conditions</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [2,2,1,2,1]
<strong>Output:</strong> 2
<strong>Explanation:</strong> 
We can satisfy the conditions by rearranging <code>arr</code> so it becomes <code>[1,2,2,2,1]</code>.
The largest element in <code>arr</code> is 2.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [100,1,1000]
<strong>Output:</strong> 3
<strong>Explanation:</strong> 
One possible way to satisfy the conditions is by doing the following:
1. Rearrange <code>arr</code> so it becomes <code>[1,100,1000]</code>.
2. Decrease the value of the second element to 2.
3. Decrease the value of the third element to 3.
Now <code>arr = [1,2,3], which </code>satisfies the conditions.
The largest element in <code>arr is 3.</code>
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [1,2,3,4,5]
<strong>Output:</strong> 5
<strong>Explanation:</strong> The array already satisfies the conditions, and the largest element is 5.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= arr.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= arr[i] &lt;= 10<sup>9</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Sort</strong></h2>



<p>arr[0] = 1,<br>arr[i] = min(arr[i], arr[i &#8211; 1] + 1)</p>



<p>ans = arr[n &#8211; 1]</p>



<p>Time complexity: O(nlogn)<br>Space complexity: O(1)</p>



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int maximumElementAfterDecrementingAndRearranging(vector&lt;int&gt;&amp; arr) {
    const int n = arr.size();
    sort(begin(arr), end(arr));
    arr[0] = 1;
    for (int i = 1; i &lt; n; ++i)
      arr[i] = min(arr[i], arr[i - 1] + 1);
    return arr.back();
  }
};</pre>
</div></div>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1846-maximum-element-after-decreasing-and-rearranging/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1838. Frequency of the Most Frequent Element</title>
		<link>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1838-frequency-of-the-most-frequent-element/</link>
					<comments>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1838-frequency-of-the-most-frequent-element/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 25 Apr 2021 16:28:49 +0000</pubDate>
				<category><![CDATA[Sliding Window]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[sliding window]]></category>
		<category><![CDATA[sort]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8388</guid>

					<description><![CDATA[The&#160;frequency&#160;of an element is the number of times it occurs in an array. You are given an integer array&#160;nums&#160;and an integer&#160;k. In one operation, you&#8230;]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1838. Frequency of the Most Frequent Element - 刷题找工作 EP392" width="500" height="281" src="https://www.youtube.com/embed/KhQOPSa09Fs?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>The&nbsp;<strong>frequency</strong>&nbsp;of an element is the number of times it occurs in an array.</p>



<p>You are given an integer array&nbsp;<code>nums</code>&nbsp;and an integer&nbsp;<code>k</code>. In one operation, you can choose an index of&nbsp;<code>nums</code>&nbsp;and increment the element at that index by&nbsp;<code>1</code>.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>maximum possible frequency</strong>&nbsp;of an element after performing&nbsp;<strong>at most</strong>&nbsp;</em><code>k</code><em>&nbsp;operations</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,4], k = 5
<strong>Output:</strong> 3<strong>
Explanation:</strong> Increment the first element three times and the second element two times to make nums = [4,4,4].
4 has a frequency of 3.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,4,8,13], k = 5
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are multiple optimal solutions:
- Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2.
- Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2.
- Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2.
</pre>



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



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



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



<ul class="wp-block-list"><li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Sliding Window</strong></h2>



<figure class="wp-block-image size-large"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1838-ep392-1.png"><img loading="lazy" decoding="async" width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1838-ep392-1.png" alt="" class="wp-image-8391" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1838-ep392-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1838-ep392-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1838-ep392-1-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></a></figure>



<figure class="wp-block-image size-large"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1838-ep392-2.png"><img loading="lazy" decoding="async" width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1838-ep392-2.png" alt="" class="wp-image-8393" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1838-ep392-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1838-ep392-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1838-ep392-2-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></a></figure>



<figure class="wp-block-image size-large"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1838-ep392-3.png"><img loading="lazy" decoding="async" width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1838-ep392-3.png" alt="" class="wp-image-8394" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1838-ep392-3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1838-ep392-3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1838-ep392-3-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></a></figure>



<p>Sort the elements, maintain a window such that it takes at most k ops to make the all the elements equal to nums[i].</p>



<p>Time complexity: O(nlogn)<br>Space complexity: O(1)</p>



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

<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  int maxFrequency(vector&lt;int&gt;&amp; nums, int k) {
    sort(begin(nums), end(nums));
    int l = 0;
    long sum = 0;
    int ans = 0;
    for (int r = 0; r &lt; nums.size(); ++r) {
      sum += nums[r];      
      while (l &lt; r &amp;&amp; 
             sum + k &lt; static_cast&lt;long&gt;(nums[r]) * (r - l + 1))
        sum -= nums[l++];
      ans = max(ans, r - l + 1);
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1838-frequency-of-the-most-frequent-element/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
