<?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>median &#8211; Huahua&#8217;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/median/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog</link>
	<description></description>
	<lastBuildDate>Sun, 06 Apr 2025 21:04:13 +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>median &#8211; Huahua&#8217;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 462. Minimum Moves to Equal Array Elements II</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-462-minimum-moves-to-equal-array-elements-ii/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-462-minimum-moves-to-equal-array-elements-ii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 06 Apr 2025 21:02:47 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[median]]></category>
		<category><![CDATA[nth_element]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10289</guid>

					<description><![CDATA[不太喜欢这样的题目，你需要证明/猜测最优解是将所有数字转换成median/中位数。 使用nth_element找中位数，然后再循环一遍求合即可。 时间复杂度：O(n)空间复杂度：O(1) [crayon-67f61dc25b4b9192469996/]]]></description>
										<content:encoded><![CDATA[
<p>不太喜欢这样的题目，你需要证明/猜测最优解是将所有数字转换成median/中位数。</p>



<p>使用nth_element找中位数，然后再循环一遍求合即可。</p>



<p>时间复杂度：O(n)<br>空间复杂度：O(1)</p>



<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  int minMoves2(vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();
    nth_element(begin(nums), begin(nums) + n / 2, end(nums));
    const int median = nums[n / 2];
    return accumulate(begin(nums), end(nums), 0, [median](int s, int x) {
      return s + abs(x - median);
    });
  }
};</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-462-minimum-moves-to-equal-array-elements-ii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>LeetCode 2033. Minimum Operations to Make a Uni-Value Grid</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-2033-minimum-operations-to-make-a-uni-value-grid/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-2033-minimum-operations-to-make-a-uni-value-grid/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 22 Oct 2021 04:23:04 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[median]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8630</guid>

					<description><![CDATA[You are given a 2D integer&#160;grid&#160;of size&#160;m x n&#160;and an integer&#160;x. In one operation, you can&#160;add&#160;x&#160;to or&#160;subtract&#160;x&#160;from any element in the&#160;grid. A&#160;uni-value grid&#160;is a grid&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a 2D integer&nbsp;<code>grid</code>&nbsp;of size&nbsp;<code>m x n</code>&nbsp;and an integer&nbsp;<code>x</code>. In one operation, you can&nbsp;<strong>add</strong>&nbsp;<code>x</code>&nbsp;to or&nbsp;<strong>subtract</strong>&nbsp;<code>x</code>&nbsp;from any element in the&nbsp;<code>grid</code>.</p>



<p>A&nbsp;<strong>uni-value grid</strong>&nbsp;is a grid where all the elements of it are equal.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>minimum</strong>&nbsp;number of operations to make the grid&nbsp;<strong>uni-value</strong></em>. If it is not possible, return&nbsp;<code>-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/gridtxt.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = [[2,4],[6,8]], x = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> We can make every element equal to 4 by doing the following: 
- Add x to 2 once.
- Subtract x from 6 once.
- Subtract x from 8 twice.
A total of 4 operations were used.
</pre>



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = [[1,5],[2,3]], x = 1
<strong>Output:</strong> 5
<strong>Explanation:</strong> We can make every element equal to 3.
</pre>



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = [[1,2],[3,4]], x = 2
<strong>Output:</strong> -1
<strong>Explanation:</strong> It is impossible to make every element equal.
</pre>



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



<ul class="wp-block-list"><li><code>m == grid.length</code></li><li><code>n == grid[i].length</code></li><li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= m * n &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= x, grid[i][j] &lt;= 10<sup>4</sup></code></li></ul>



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



<p>To achieve minimum operations, the uni-value must be the median of the array.</p>



<p>Time complexity: O(m*n)<br>Space complexity: O(m*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 minOperations(vector&lt;vector&lt;int&gt;&gt;&amp; grid, int x) {
    const int mn = grid.size() * grid[0].size();    
    vector&lt;int&gt; nums;
    nums.reserve(mn);
    for (const auto&amp; row : grid)
      nums.insert(end(nums), begin(row), end(row));
    nth_element(begin(nums), begin(nums) + mn / 2, end(nums));
    const int median = nums[mn / 2];
    int ans = 0;
    for (int v : nums) {
      if (abs(v - median) % x) return -1;
      ans += abs(v - median) / x;
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/math/leetcode-2033-minimum-operations-to-make-a-uni-value-grid/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1478. Allocate Mailboxes</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1478-allocate-mailboxes/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1478-allocate-mailboxes/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 14 Jun 2020 07:29:32 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[median]]></category>
		<category><![CDATA[paritition]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6916</guid>

					<description><![CDATA[Given the array&#160;houses&#160;and an integer&#160;k. where&#160;houses[i]&#160;is the location of the ith house along a street, your task is to allocate&#160;k&#160;mailboxes in&#160;the street. Return the&#160;minimum&#160;total distance&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Given the array&nbsp;<code>houses</code>&nbsp;and an integer&nbsp;<code>k</code>. where&nbsp;<code>houses[i]</code>&nbsp;is the location of the ith house along a street, your task is to allocate&nbsp;<code>k</code>&nbsp;mailboxes in&nbsp;the street.</p>



<p>Return the&nbsp;<strong>minimum</strong>&nbsp;total distance between each house and its nearest mailbox.</p>



<p>The answer is guaranteed to fit in a 32-bit signed integer.</p>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2020/05/07/sample_11_1816.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> houses = [1,4,8,10,20], k = 3
<strong>Output:</strong> 5
<strong>Explanation: </strong>Allocate mailboxes in position 3, 9 and 20.
Minimum total distance from each houses to nearest mailboxes is |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5 
</pre>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2020/05/07/sample_2_1816.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> houses = [2,3,5,12,18], k = 2
<strong>Output:</strong> 9
<strong>Explanation: </strong>Allocate mailboxes in position 3 and 14.
Minimum total distance from each houses to nearest mailboxes is |2-3| + |3-3| + |5-3| + |12-14| + |18-14| = 9.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> houses = [7,4,6,1], k = 1
<strong>Output:</strong> 8
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> houses = [3,6,14,10], k = 4
<strong>Output:</strong> 0
</pre>



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



<ul class="wp-block-list"><li><code>n == houses.length</code></li><li><code>1 &lt;= n&nbsp;&lt;= 100</code></li><li><code>1 &lt;= houses[i] &lt;= 10^4</code></li><li><code>1 &lt;= k &lt;= n</code></li><li>Array&nbsp;<code>houses</code>&nbsp;contain unique integers.</li></ul>



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



<p>First, we need to sort the houses by their location.</p>



<p>This is a partitioning problem, e.g. optimal solution to partition first N houses into K groups. (allocating K mailboxes for the first N houses).</p>



<p>The key of this problem is to solve a base case, optimally allocating one mailbox for houses[i~j], The intuition is to put the mailbox in the middle location, this only works if there are only tow houses, or all the houses are evenly distributed. The correct location is the &#8220;median position&#8221; of a set of houses. For example, if the sorted locations are [1,2,3,100], the average will be 26 which costs 146 while the median is 2, and the cost becomes 100.</p>



<p>dp[i][k] := min cost to allocate k mailboxes houses[0~i].</p>



<p>base cases: </p>



<ol class="wp-block-list"><li>dp[i][1] = cost(0, i), min cost to allocate one mailbox.</li><li>dp[i][k] = 0 if k &gt; i, more mailboxes than houses. // this is actually a pruning.</li></ol>



<p>transition:</p>



<p>dp[i][k] = min(dp[p][k-1] + cost(p + 1, i)) 0 &lt;= p &lt; i,</p>



<p>allocate k-1 mailboxes for houses[0~p], and allocate one for houses[p+1~i]</p>



<p>ans:</p>



<p>dp[n-1][k]</p>



<p>Time complexity: O(n^3)<br>Space complexity: O(n^2) -&gt; 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 minDistance(vector&lt;int&gt;&amp; houses, int k) {
    constexpr int kInf = 1e9;
    const int n = houses.size();
    sort(begin(houses), end(houses));
    vector&lt;vector&lt;int&gt;&gt; dp(n + 1, vector&lt;int&gt;(n + 1, kInf));
    vector&lt;vector&lt;int&gt;&gt; costs(n + 1, vector&lt;int&gt;(n + 1, kInf));
    // min cost to allocate one mailbox for houses[i~j].
    auto cost = [&amp;](int i, int j) {
      int&amp; ans = costs[i][j];
      if (ans != kInf) return ans;
      const int m = i + (j - i) / 2;
      int box = 0;
      if ((j - i + 1) &amp; 1) // odd number of houses.
        box = houses[m];
      else // even number of houses.
        box = (houses[m] + houses[m + 1]) / 2;
      ans = 0;
      for (int h = i; h &lt;= j; ++h)
        ans += abs(houses[h] - box);
      return ans;
    };
    // min cost to allocate k mailboxes for houses[0~i].
    function&lt;int(int, int)&gt; solve = [&amp;](int i, int k) {
      if (k &gt; i) return 0; // more mailboxs than houses.
      if (k == 1) return cost(0, i);
      int&amp; ans = dp[i][k];
      if (ans != kInf) return ans;
      for (int p = 0; p &lt; i; ++p)
        ans = min(ans, solve(p, k - 1) + cost(p + 1, i));
      return ans;
    };
    return solve(n - 1, k);
  }
};</pre>
</div></div>



<p>O(1) time to compute cost. O(n) Time and space for pre-processing.</p>



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
vector&lt;int&gt; sums(n + 1);
for (int i = 1; i &lt;= n; ++i)
  sums[i] = sums[i - 1] + houses[i - 1];
// min cost to allocate one mailbox for houses[i~j].
auto cost = [&amp;](int i, int j) {      
  const int m1 = (i + j) / 2;
  const int m2 = (i + j + 1) / 2;
  const int center = (houses[m1] + houses[m2]) / 2;
  return (m1 - i + 1) * center - (sums[m1 + 1] - sums[i])
       + (sums[j + 1] - sums[m2]) - (j - m2 + 1) * center;
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1478-allocate-mailboxes/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1471. The k Strongest Values in an Array</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1471-the-k-strongest-values-in-an-array/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1471-the-k-strongest-values-in-an-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 07 Jun 2020 05:30:36 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[median]]></category>
		<category><![CDATA[quickselect]]></category>
		<category><![CDATA[sorting]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6883</guid>

					<description><![CDATA[Given an array of integers&#160;arr&#160;and an integer&#160;k. A value&#160;arr[i]&#160;is said to be stronger than a value&#160;arr[j]&#160;if&#160;&#124;arr[i] - m&#124; &#62; &#124;arr[j]&#160;- m&#124;&#160;where&#160;m&#160;is the&#160;median&#160;of the array.If&#160;&#124;arr[i] -&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Given an array of integers&nbsp;<code>arr</code>&nbsp;and an integer&nbsp;<code>k</code>.</p>



<p>A value&nbsp;<code>arr[i]</code>&nbsp;is said to be stronger than a value&nbsp;<code>arr[j]</code>&nbsp;if&nbsp;<code>|arr[i] - m| &gt; |arr[j]&nbsp;- m|</code>&nbsp;where&nbsp;<code>m</code>&nbsp;is the&nbsp;<strong>median</strong>&nbsp;of the array.<br>If&nbsp;<code>|arr[i] - m| == |arr[j] - m|</code>, then&nbsp;<code>arr[i]</code>&nbsp;is said to be stronger than&nbsp;<code>arr[j]</code>&nbsp;if&nbsp;<code>arr[i] &gt; arr[j]</code>.</p>



<p>Return&nbsp;<em>a list of the strongest&nbsp;<code>k</code></em>&nbsp;values in the array. return the answer&nbsp;<strong>in any arbitrary order</strong>.</p>



<p><strong>Median</strong>&nbsp;is the middle value in an ordered integer list. More formally, if the length of the list is n, the median is the element in position&nbsp;<code>((n - 1) / 2)</code>&nbsp;in the sorted list&nbsp;<strong>(0-indexed)</strong>.</p>



<ul class="wp-block-list"><li>For&nbsp;<code>arr =&nbsp;[6, -3, 7, 2, 11]</code>,&nbsp;<code>n = 5</code>&nbsp;and the median is obtained by sorting the array&nbsp;<code>arr = [-3, 2, 6, 7, 11]</code>&nbsp;and the median is&nbsp;<code>arr[m]</code>&nbsp;where&nbsp;<code>m = ((5 - 1) / 2) = 2</code>. The median is&nbsp;<code>6</code>.</li><li>For&nbsp;<code>arr =&nbsp;[-7, 22, 17, 3]</code>,&nbsp;<code>n = 4</code>&nbsp;and the median is obtained by sorting the array&nbsp;<code>arr = [-7, 3, 17, 22]</code>&nbsp;and the median is&nbsp;<code>arr[m]</code>&nbsp;where&nbsp;<code>m = ((4 - 1) / 2) = 1</code>. The median is&nbsp;<code>3</code>.</li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [1,2,3,4,5], k = 2
<strong>Output:</strong> [5,1]
<strong>Explanation:</strong> Median is 3, the elements of the array sorted by the strongest are [5,1,4,2,3]. The strongest 2 elements are [5, 1]. [1, 5] is also <strong>accepted</strong> answer.
Please note that although |5 - 3| == |1 - 3| but 5 is stronger than 1 because 5 &gt; 1.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [1,1,3,5,5], k = 2
<strong>Output:</strong> [5,5]
<strong>Explanation:</strong> Median is 3, the elements of the array sorted by the strongest are [5,5,1,1,3]. The strongest 2 elements are [5, 5].
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [6,7,11,7,6,8], k = 5
<strong>Output:</strong> [11,8,6,6,7]
<strong>Explanation:</strong> Median is 7, the elements of the array sorted by the strongest are [11,8,6,6,7,7].
Any permutation of [11,8,6,6,7] is <strong>accepted</strong>.
</pre>



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



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



<p><strong>Example 5:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [-7,22,17,3], k = 2
<strong>Output:</strong> [22,17]
</pre>



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



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



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



<p>Step 1: find the median element m<br>Step 2: Sort the array according to m<br>Step 3: output the first k elements of the sorted array.</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:
  vector&lt;int&gt; getStrongest(vector&lt;int&gt;&amp; arr, int k) {
    const int n = arr.size();
    const int i = (n - 1) / 2;
    // sort(begin(arr), end(arr));
    nth_element(begin(arr), begin(arr) + i, end(arr));
    const int m = arr[i];  
    sort(begin(arr), end(arr), [&amp;](const int x, const int y) {      
      return abs(x - m) != abs(y - m) ? abs(x - m) &gt; abs(y - m) : x &gt; y;      
    });    
    return {begin(arr), begin(arr) + k};
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1471-the-k-strongest-values-in-an-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1093. Statistics from a Large Sample</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1093-statistics-from-a-large-sample/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1093-statistics-from-a-large-sample/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 07 Feb 2020 05:38:00 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[median]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[mode]]></category>
		<category><![CDATA[statistics]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6266</guid>

					<description><![CDATA[We sampled integers between&#160;0&#160;and&#160;255, and stored the results in an array&#160;count:&#160;&#160;count[k]&#160;is the number of integers we sampled equal to&#160;k. Return the minimum, maximum, mean, median,&#8230;]]></description>
										<content:encoded><![CDATA[
<p>We sampled integers between&nbsp;<code>0</code>&nbsp;and&nbsp;<code>255</code>, and stored the results in an array&nbsp;<code>count</code>:&nbsp;&nbsp;<code>count[k]</code>&nbsp;is the number of integers we sampled equal to&nbsp;<code>k</code>.</p>



<p>Return the minimum, maximum, mean, median, and mode of the sample respectively, as an array of&nbsp;<strong>floating point numbers</strong>.&nbsp; The mode is guaranteed to be unique.</p>



<p><em>(Recall that the median of a sample is:</em></p>



<ul class="wp-block-list"><li><em>The middle element, if the elements of the sample were sorted and the number of elements is odd;</em></li><li><em>The average of the middle two elements, if the elements of the sample were sorted and the number of elements is even.)</em></li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> count = [0,1,3,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
<strong>Output:</strong> [1.00000,3.00000,2.37500,2.50000,3.00000]
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> count = [0,4,3,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
<strong>Output:</strong> [1.00000,4.00000,2.18182,2.00000,1.00000]
</pre>



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



<ol class="wp-block-list"><li><code>count.length == 256</code></li><li><code>1 &lt;= sum(count) &lt;= 10^9</code></li><li>The mode of the sample that count represents is unique.</li><li>Answers within&nbsp;<code>10^-5</code>&nbsp;of the true value will be accepted as correct.</li></ol>



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



<p>Time complexity: O(1)<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:
  vector&lt;double&gt; sampleStats(vector&lt;int&gt;&amp; count) {
    int counts = 0;
    int minVal = 255;
    int maxVal = 0;
    int mode = -1;
    int modeCount = 0;
    long sum = 0;
    map&lt;int, int&gt; m;
    for (int i = 0; i &lt;= 255; ++i) {      
      if (!count[i]) continue;
      sum += static_cast&lt;long&gt;(i) * count[i];
      minVal = min(minVal, i);
      maxVal = max(maxVal, i);
      if (count[i] &gt; modeCount) {
        mode = i;
        modeCount = count[i];
      }
      m[counts += count[i]] = i;
    }
    auto it1 = m.lower_bound(counts / 2);
    double median = it1-&gt;second;    
    auto it2 = next(it1);
    if (counts % 2 == 0 &amp;&amp; it2 != m.end() &amp;&amp; it1-&gt;first == counts / 2) {  
      median = (median + it2-&gt;second) / 2;
    }
    return {minVal, maxVal, static_cast&lt;double&gt;(sum) / counts, median, mode};
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1093-statistics-from-a-large-sample/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 480. Sliding Window Median</title>
		<link>https://zxi.mytechroad.com/blog/difficulty/hard/leetcode-480-sliding-window-median/</link>
					<comments>https://zxi.mytechroad.com/blog/difficulty/hard/leetcode-480-sliding-window-median/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 28 Jan 2018 08:56:53 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[Hard]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[median]]></category>
		<category><![CDATA[sliding window]]></category>
		<category><![CDATA[sorting]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1672</guid>

					<description><![CDATA[题目大意：让你求移动窗口的中位数。 Problem: Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value.&#8230;]]></description>
										<content:encoded><![CDATA[<p><iframe title="花花酱 LeetCode 480. Sliding Window Median - 刷题找工作 EP162" width="500" height="375" src="https://www.youtube.com/embed/kDS6ScZwNnI?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></p>
<p>题目大意：让你求移动窗口的中位数。</p>
<p><strong>Problem:</strong></p>
<p>Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.</p>
<p>Examples:</p>
<p><code>[2,3,4]</code>&nbsp;, the median is&nbsp;<code>3</code></p>
<p><code>[2,3]</code>, the median is&nbsp;<code>(2 + 3) / 2 = 2.5</code></p>
<p>Given an array&nbsp;<i>nums</i>, there is a sliding window of size&nbsp;<i>k</i>&nbsp;which is moving from the very left of the array to the very right. You can only see the&nbsp;<i>k</i>&nbsp;numbers in the window. Each time the sliding window moves right by one position. Your job is to output the median array for each window in the original array.</p>
<p>For example,<br />
Given&nbsp;<i>nums</i>&nbsp;=&nbsp;<code>[1,3,-1,-3,5,3,6,7]</code>, and&nbsp;<i>k</i>&nbsp;= 3.</p><pre class="urvanov-syntax-highlighter-plain-tag">Window position                Median
---------------               -----
[1  3  -1] -3  5  3  6  7       1
 1 [3  -1  -3] 5  3  6  7       -1
 1  3 [-1  -3  5] 3  6  7       -1
 1  3  -1 [-3  5  3] 6  7       3
 1  3  -1  -3 [5  3  6] 7       5
 1  3  -1  -3  5 [3  6  7]      6</pre><p>Therefore, return the median sliding window as&nbsp;<code>[1,-1,-1,3,5,6]</code>.</p>
<p><b>Note:&nbsp;</b><br />
You may assume&nbsp;<code>k</code>&nbsp;is always valid, ie:&nbsp;<code>k</code>&nbsp;is always smaller than input array&#8217;s size for non-empty array.</p>
<p><script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><br />
<ins class="adsbygoogle" style="display:block" data-ad-format="fluid" data-ad-layout-key="-fb+5w+4e-db+86" data-ad-client="ca-pub-2404451723245401" data-ad-slot="2162692788"></ins><br />
<script><br />
     (adsbygoogle = window.adsbygoogle || []).push({});<br />
</script></p>
<p><img fetchpriority="high" decoding="async" class="alignnone size-full wp-image-1695" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/480-ep162-0.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/480-ep162-0.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/480-ep162-0-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/480-ep162-0-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p><img decoding="async" class="alignnone size-full wp-image-1696" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/480-ep162-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/480-ep162-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/480-ep162-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/480-ep162-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p><img loading="lazy" decoding="async" class="alignnone size-full wp-image-1698" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/480-ep162-2-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/480-ep162-2-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/480-ep162-2-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/480-ep162-2-1-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></p>
<p><strong>Solution 0: Brute Force</strong></p>
<p>Time complexity: O(n*klogk) TLE 32/42 test cases passed</p>
<p><b>Solution 1: Insertion&nbsp;Sort</b></p>
<p>Time complexity: O(k*logk +&nbsp; (n &#8211; k + 1)*k)</p>
<p>Space complexity: O(k)</p>
<p>C++ / vector</p><pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
// Running time: 99 ms
class Solution {
public:
  vector&lt;double&gt; medianSlidingWindow(vector&lt;int&gt;&amp; nums, int k) {    
    vector&lt;double&gt; ans;
    if (k == 0) return ans;
    vector&lt;int&gt; window(nums.begin(), nums.begin() + k - 1);
    std::sort(window.begin(), window.end());
    for (int i = k - 1; i &lt; nums.size(); ++i) {
      window.push_back(nums[i]);
      auto it = prev(window.end(), 1);
      auto const insertion_point = 
              std::upper_bound(window.begin(), it, *it);      
      std::rotate(insertion_point, it, it + 1);          
      ans.push_back((static_cast&lt;double&gt;(window[k / 2]) + window[(k - 1) / 2]) / 2);
      window.erase(std::find(window.begin(), window.end(), nums[i - k + 1]));      
    }
    return ans;
  }
};</pre><p>C++ / vector + binary_search for deletion.</p><pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
// Running time: 84 ms
class Solution {
public:
  vector&lt;double&gt; medianSlidingWindow(vector&lt;int&gt;&amp; nums, int k) {    
    vector&lt;double&gt; ans;
    if (k == 0) return ans;
    vector&lt;int&gt; window(nums.begin(), nums.begin() + k - 1);
    std::sort(window.begin(), window.end());
    for (int i = k - 1; i &lt; nums.size(); ++i) {
      window.push_back(nums[i]);
      auto it = prev(window.end(), 1);
      auto const insertion_point = 
              std::upper_bound(window.begin(), it, *it);      
      std::rotate(insertion_point, it, it + 1);          
      ans.push_back((static_cast&lt;double&gt;(window[k / 2]) + window[(k - 1) / 2]) / 2);
      window.erase(std::lower_bound(window.begin(), window.end(), nums[i - k + 1]));      
    }
    return ans;
  }
};</pre><p>Java</p><pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
// Running time: 60 ms
class Solution {
  public double[] medianSlidingWindow(int[] nums, int k) {
    if (k == 0) return new double[0];
    double[] ans = new double[nums.length - k + 1];
    int[] window = new int[k];
    for (int i = 0; i &lt; k; ++i) 
      window[i] = nums[i];
    Arrays.sort(window);
    for (int i = k; i &lt;= nums.length; ++i) {
      ans[i - k] = ((double)window[k / 2] + window[(k - 1)/2]) / 2;
      if (i == nums.length) break;
      remove(window, nums[i - k]);
      insert(window, nums[i]);
    }
    return ans;
  }
  
  // Insert val into window, window[k - 1] is empty before inseration
  private void insert(int[] window, int val) {
    int i = 0;
    while (i &lt; window.length - 1 &amp;&amp; val &gt; window[i]) ++i;
    int j = window.length - 1;
    while (j &gt; i) window[j] = window[--j];
    window[j] = val;
  }
  
  // Remove val from window and shrink it.
  private void remove(int[] window, int val) {
    int i = 0;
    while (i &lt; window.length &amp;&amp; val != window[i]) ++i;
    while (i &lt; window.length - 1) window[i] = window[++i];
  }
}</pre><p>Java / Binary Search</p><pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
// Running time: 47 ms (&lt;98.96%)
class Solution {
  public double[] medianSlidingWindow(int[] nums, int k) {
    if (k == 0) return new double[0];
    double[] ans = new double[nums.length - k + 1];
    int[] window = new int[k];
    for (int i = 0; i &lt; k; ++i) 
      window[i] = nums[i];
    Arrays.sort(window);
    for (int i = k; i &lt;= nums.length; ++i) {
      ans[i - k] = ((double)window[k / 2] + window[(k - 1)/2]) / 2;
      if (i == nums.length) break;
      remove(window, nums[i - k]);
      insert(window, nums[i]);
    }
    return ans;
  }
  
  // Insert val into window, window[k - 1] is empty before inseration
  private void insert(int[] window, int val) {
    int i = Arrays.binarySearch(window, val);
    if (i &lt; 0) i = - i - 1;    
    int j = window.length - 1;
    while (j &gt; i) window[j] = window[--j];
    window[j] = val;
  }
  
  // Remove val from window and shrink it.
  private void remove(int[] window, int val) {
    int i = Arrays.binarySearch(window, val);
    while (i &lt; window.length - 1) window[i] = window[++i];
  }
  
  
}</pre><p>&nbsp;</p>
<p>Python</p><pre class="urvanov-syntax-highlighter-plain-tag">"""
Author: Huahua
Running time: 161 ms (&lt; 93.75%)
"""
class Solution:
  def medianSlidingWindow(self, nums, k):
    if k == 0: return []
    ans = []
    window = sorted(nums[0:k])
    for i in range(k, len(nums) + 1):
      ans.append((window[k // 2] + window[(k - 1) // 2]) / 2.0)
      if i == len(nums): break
      index = bisect.bisect_left(window, nums[i - k])
      window.pop(index)      
      bisect.insort_left(window, nums[i])
    return ans</pre><p><strong>Solution 2: BST</strong></p><pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
// Running time: 68 ms
class Solution {
public:
  vector&lt;double&gt; medianSlidingWindow(vector&lt;int&gt;&amp; nums, int k) {    
    vector&lt;double&gt; ans;
    if (k == 0) return ans;
    multiset&lt;int&gt; window(nums.begin(), nums.begin() + k);
    auto mid = next(window.begin(), (k - 1) / 2);    
    for (int i = k; i &lt;= nums.size(); ++i) {
      ans.push_back((static_cast&lt;double&gt;(*mid) + 
                     *next(mid, (k + 1) % 2)) / 2.0);
      if (i == nums.size()) break;
      
      window.insert(nums[i]);
      if (nums[i] &lt; *mid) --mid; 
      if (nums[i - k] &lt;= *mid) ++mid;
      window.erase(window.lower_bound(nums[i - k])); 
    }
    return ans;
  }
};</pre><p>&nbsp;</p>
<p><strong>Related Problems:</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/leetcode/leetcode-295-find-median-from-data-stream/">[解题报告] LeetCode 295. Find Median from Data Stream O(logn) + O(1)</a></li>
<li><a href="http://zxi.mytechroad.com/blog/heap/leetcode-239-sliding-window-maximum/">花花酱 LeetCode 239. Sliding Window Maximum</a></li>
</ul>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/difficulty/hard/leetcode-480-sliding-window-median/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode  4. Median of Two Sorted Arrays</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-4-median-of-two-sorted-arrays/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-4-median-of-two-sorted-arrays/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 08 Nov 2017 16:33:09 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[Hard]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[median]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=747</guid>

					<description><![CDATA[题目大意：求两个已经排序的数组的中位数（如果合并后）。 Problem: There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity&#8230;]]></description>
										<content:encoded><![CDATA[<p><iframe loading="lazy" title="花花酱 LeetCode 4. Median of Two Sorted Arrays - 刷题找工作 EP102" width="500" height="375" src="https://www.youtube.com/embed/KB9IcSCDQ9k?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></p>
<p>题目大意：求两个已经排序的数组的中位数（如果合并后）。</p>
<p><strong>Problem:</strong></p>
<p>There are two sorted arrays <b>nums1</b> and <b>nums2</b> of size m and n respectively.</p>
<p>Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).</p>
<p><b>Example 1:</b></p><pre class="urvanov-syntax-highlighter-plain-tag">nums1 = [1, 3]
nums2 = [2]

The median is 2.0</pre><p><b>Example 2:</b></p><pre class="urvanov-syntax-highlighter-plain-tag">nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5</pre><p><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><br />
<ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-2404451723245401" data-ad-slot="7983117522"></ins><br />
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<p><strong>Idea:</strong></p>
<p>Binary Search</p>
<p>Time complexity: O(log(min(n1,n2)))</p>
<p>Space complexity: O(1)</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/4-ep102.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-755" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/4-ep102.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/4-ep102.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/4-ep102-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/4-ep102-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/4-ep102-624x351.png 624w" sizes="auto, (max-width: 960px) 100vw, 960px" /></a></p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/4-ep102-2.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-754" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/4-ep102-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/4-ep102-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/4-ep102-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/4-ep102-2-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/4-ep102-2-624x351.png 624w" sizes="auto, (max-width: 960px) 100vw, 960px" /></a></p>
<p><ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-2404451723245401" data-ad-slot="7983117522"> </ins></p>
<h1><strong>Solution: Binary Search</strong></h1>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
// Runtime: 52 ms
class Solution {
public:
    double findMedianSortedArrays(vector&lt;int&gt;&amp; nums1, vector&lt;int&gt;&amp; nums2) {
        const int n1 = nums1.size();
        const int n2 = nums2.size();
        // Make sure n1 &lt;= n2
        if (n1 &gt; n2) return findMedianSortedArrays(nums2, nums1);
        
        const int k = (n1 + n2 + 1) / 2;

        int l = 0;
        int r = n1;
               
        while (l &lt; r) {
            const int m1 = l + (r - l) / 2;
            const int m2 = k - m1;
            if (nums1[m1] &lt; nums2[m2 - 1])
                l = m1 + 1;
            else
                r = m1;
        }
        
        const int m1 = l;
        const int m2 = k - l;
        
        const int c1 = max(m1 &lt;= 0 ? INT_MIN : nums1[m1 - 1], 
                           m2 &lt;= 0 ? INT_MIN : nums2[m2 - 1]);

        if ((n1 + n2) % 2 == 1)
            return c1;    
        
        const int c2 = min(m1 &gt;= n1 ? INT_MAX : nums1[m1], 
                           m2 &gt;= n2 ? INT_MAX : nums2[m2]);
                
        return (c1 + c2) * 0.5;
    }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
// Runtime: 66 ms
class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int n1 = nums1.length;
        int n2 = nums2.length;
        if (n1 &gt; n2) 
            return findMedianSortedArrays(nums2, nums1);
        
        int k = (n1 + n2 + 1) / 2;
        int l = 0;
        int r = n1;
               
        while (l &lt; r) {
            int m1 = l + (r - l) / 2;
            int m2 = k - m1;
            if (nums1[m1] &lt; nums2[m2 - 1])
                l = m1 + 1;
            else
                r = m1;
        }
        
        int m1 = l;
        int m2 = k - l;
        
        int c1 = Math.max(m1 &lt;= 0 ? Integer.MIN_VALUE : nums1[m1 - 1], 
                          m2 &lt;= 0 ? Integer.MIN_VALUE : nums2[m2 - 1]);

        if ((n1 + n2) % 2 == 1)
            return c1;    
        
        int c2 = Math.min(m1 &gt;= n1 ? Integer.MAX_VALUE : nums1[m1], 
                          m2 &gt;= n2 ? Integer.MAX_VALUE : nums2[m2]);
                
        return (c1 + c2) * 0.5;
    }
}</pre><p></div></div></p>
<h1><strong>Related Problem:</strong></h1>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/leetcode/leetcode-295-find-median-from-data-stream/">[解题报告] LeetCode 295. Find Median from Data Stream O(logn) + O(1)</a></li>
</ul>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-4-median-of-two-sorted-arrays/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 295. Find Median from Data Stream O(logn) + O(1)</title>
		<link>https://zxi.mytechroad.com/blog/leetcode/leetcode-295-find-median-from-data-stream/</link>
					<comments>https://zxi.mytechroad.com/blog/leetcode/leetcode-295-find-median-from-data-stream/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 12 Sep 2017 08:01:52 +0000</pubDate>
				<category><![CDATA[Data Structure]]></category>
		<category><![CDATA[Heap]]></category>
		<category><![CDATA[Leetcode]]></category>
		<category><![CDATA[Tree]]></category>
		<category><![CDATA[BST]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[median]]></category>
		<category><![CDATA[online]]></category>
		<category><![CDATA[priority queue]]></category>
		<category><![CDATA[stream]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=243</guid>

					<description><![CDATA[Problem: Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So&#8230;]]></description>
										<content:encoded><![CDATA[<p><iframe loading="lazy" title="花花酱 LeetCode 295. Find Median from Data Stream - 刷题找工作 EP51" width="500" height="375" src="https://www.youtube.com/embed/60xnYZ21Ir0?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></p>
<p><strong>Problem:</strong></p>
<p>Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.</p>
<p>Examples:</p>
<p><code>[2,3,4]</code> , the median is <code>3</code></p>
<p><code>[2,3]</code>, the median is <code>(2 + 3) / 2 = 2.5</code></p>
<p>Design a data structure that supports the following two operations:</p>
<ul>
<li>void addNum(int num) &#8211; Add a integer number from the data stream to the data structure.</li>
<li>double findMedian() &#8211; Return the median of all elements so far.</li>
</ul>
<p>For example:</p><pre class="urvanov-syntax-highlighter-plain-tag">addNum(1)
addNum(2)
findMedian() = 1.5
addNum(3) 
findMedian() = 2</pre><p>&nbsp;</p>
<p><strong>Idea</strong>:</p>
<ol>
<li>Min/Max heap</li>
<li>Balanced binary search tree</li>
</ol>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/295-ep51-1.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-248" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/295-ep51-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/295-ep51-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/295-ep51-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/295-ep51-1-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/295-ep51-1-624x351.png 624w" sizes="auto, (max-width: 960px) 100vw, 960px" /></a><img loading="lazy" decoding="async" class="alignnone size-full wp-image-247" style="font-size: 1rem;" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/295-ep51-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/295-ep51-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/295-ep51-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/295-ep51-2-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/295-ep51-2-624x351.png 624w" sizes="auto, (max-width: 960px) 100vw, 960px" /><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/295-ep51-3.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-246" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/295-ep51-3.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/295-ep51-3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/295-ep51-3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/295-ep51-3-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/295-ep51-3-624x351.png 624w" sizes="auto, (max-width: 960px) 100vw, 960px" /></a></p>
<p><strong>Time Complexity</strong>:</p>
<p>add(num): O(logn)</p>
<p>findMedian(): O(logn)</p>
<p><strong>Solution1</strong>:</p><pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
// Running Time: 152 ms
class MedianFinder {
public:
    /** initialize your data structure here. */
    MedianFinder() {}
    
    // l_.size() &gt;= r_.size()
    void addNum(int num) {
        if (l_.empty() || num &lt;= l_.top()) {
            l_.push(num);
        } else {
            r_.push(num);
        }
        
        // Step 2: Balence left/right
        if (l_.size() &lt; r_.size()) {
            l_.push(r_.top());
            r_.pop();
        } else if (l_.size() - r_.size() == 2) {
            r_.push(l_.top());
            l_.pop();
        }
    }
    
    double findMedian() {
        if (l_.size() &gt; r_.size()) {
            return static_cast&lt;double&gt;(l_.top());
        } else {            
            return (static_cast&lt;double&gt;(l_.top()) + r_.top()) / 2;
        }
    }
private:
    priority_queue&lt;int, vector&lt;int&gt;, less&lt;int&gt;&gt; l_;    // max-heap
    priority_queue&lt;int, vector&lt;int&gt;, greater&lt;int&gt;&gt; r_; // min-heap
};</pre><p>&nbsp;</p>
<p><strong>Solution 2:</strong></p><pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
// Running time: 172 ms
class MedianFinder {
public:
    /** initialize your data structure here. */
    MedianFinder(): l_(m_.cend()), r_(m_.cend()) {}
    
    // O(logn)
    void addNum(int num) {
        if (m_.empty()) {
            l_ = r_ = m_.insert(num);
            return;
        }
        
        m_.insert(num);
        const size_t n = m_.size();    
        
        if (n &amp; 1) {
            // odd number
            if (num &gt;= *r_) {         
                l_ = r_;
            } else {
                // num &lt; *r_, l_ could be invalidated
                l_ = --r_;
            }
        } else {
            if (num &gt;= *r_)
                ++r_;
            else
                --l_;
        }
    }
    // O(1)
    double findMedian() {
        return (static_cast&lt;double&gt;(*l_) + *r_) / 2;
    }
private:
    multiset&lt;int&gt; m_;
    multiset&lt;int&gt;::const_iterator l_;  // current left median
    multiset&lt;int&gt;::const_iterator r_;  // current right median
};</pre><p>&nbsp;</p>
<p><strong>Related Problems</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/difficulty/hard/leetcode-480-sliding-window-median/">花花酱 LeetCode 480. Sliding Window Median</a></li>
<li><a href="http://zxi.mytechroad.com/blog/binary-search/leetcode-4-median-of-two-sorted-arrays/">[解题报告] LeetCode 4. Median of Two Sorted Arrays</a></li>
<li><a href="http://zxi.mytechroad.com/blog/zoj/zoj-3612-median/">[ZOJ] 3612: Median</a></li>
</ul>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/leetcode/leetcode-295-find-median-from-data-stream/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>[ZOJ] 3612: Median</title>
		<link>https://zxi.mytechroad.com/blog/zoj/zoj-3612-median/</link>
					<comments>https://zxi.mytechroad.com/blog/zoj/zoj-3612-median/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 13 Mar 2017 02:51:59 +0000</pubDate>
				<category><![CDATA[ZOJ]]></category>
		<category><![CDATA[binary_search]]></category>
		<category><![CDATA[dynamic]]></category>
		<category><![CDATA[median]]></category>
		<category><![CDATA[sorting]]></category>
		<category><![CDATA[vector]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=17</guid>

					<description><![CDATA[[crayon-67f61dc25f83d466387631/] &#160;]]></description>
										<content:encoded><![CDATA[<p></p><pre class="urvanov-syntax-highlighter-plain-tag">// 3934633  2017-03-13 10:48:25 Accepted  3612  C++0x 900 540 xxfflower
#include &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;unordered_map&gt;
#include &lt;algorithm&gt;
#include &lt;queue&gt;
#include &lt;set&gt;
using namespace std;
typedef long long int64;

int main() {
  int t,n,x;
  char op[20];
  cin&gt;&gt;t;

  while(t--) {
    scanf("%d", &amp;n);
    
    vector&lt;int64&gt; a;

    while(n--) {
      scanf("%s %d", op, &amp;x);
      auto it = lower_bound(a.begin(), a.end(), x);

      if(op[0] == 'r') {
        if(it==a.end() || *it != x) {
          puts("Wrong!");
          continue;
        } else {
          a.erase(it);
          if(a.empty()) {
            puts("Empty!");
            continue;
          }
        }
      } else if(op[0] == 'a') {
        a.insert(it, x);
      }

      if(a.size()%2==1) {
        printf("%lld\n", a[a.size()/2]);
      } else {
        int64 ans = a[a.size()/2-1] + a[a.size()/2];
        if(ans%2==0) 
          printf("%lld\n", ans/2);
        else 
          printf("%.1lf\n", ans/2.0);
      }
    }
  }

  return 0;
}</pre><p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/zoj/zoj-3612-median/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
