<?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>binary indexed tree Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/binary-indexed-tree/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/binary-indexed-tree/</link>
	<description></description>
	<lastBuildDate>Tue, 14 Apr 2020 03:43:20 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.8</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>binary indexed tree Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/binary-indexed-tree/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 Fenwick Tree / Binary Indexed Tree / 树状数组 SP3</title>
		<link>https://zxi.mytechroad.com/blog/sp/fenwick-tree-binary-indexed-tree-sp3/</link>
					<comments>https://zxi.mytechroad.com/blog/sp/fenwick-tree-binary-indexed-tree-sp3/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 04 Jan 2018 07:09:20 +0000</pubDate>
				<category><![CDATA[SP]]></category>
		<category><![CDATA[binary indexed tree]]></category>
		<category><![CDATA[fenwick tree]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1491</guid>

					<description><![CDATA[<p>本期节目中我们介绍了Fenwick Tree/Binary Indexed Tree/树状数组的原理和实现以及它在leetcode中的应用。 In this episode, we will introduce Fenwick Tree/Binary Indexed Tree, its idea and implementation and show its applications in leetcode. Fenwick&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/sp/fenwick-tree-binary-indexed-tree-sp3/">花花酱 Fenwick Tree / Binary Indexed Tree / 树状数组 SP3</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe title="花花酱 Fenwick Tree / Binary Indexed Tree - 刷题找工作 SP3" width="500" height="375" src="https://www.youtube.com/embed/WbafSgetDDk?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></p>
<p>本期节目中我们介绍了Fenwick Tree/Binary Indexed Tree/树状数组的原理和实现以及它在leetcode中的应用。<br>
In this episode, we will introduce Fenwick Tree/Binary Indexed Tree, its idea and implementation and show its applications in leetcode.</p>
<p>Fenwick Tree is mainly designed for solving the single point update range sum problems. e.g. what&#8217;s the sum between i-th and j-th element while the values of the elements are mutable.</p>
<p>Init the tree (include building all prefix sums) takes O(nlogn)</p>
<p>Update the value of an element takes O(logn)</p>
<p>Query the range sum takes O(logn)</p>
<p>Space complexity: O(n)</p>
<p><img class="alignnone size-full wp-image-1496" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/sp3-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/sp3-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/sp3-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/sp3-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p><script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script></p>
<p><ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-2404451723245401" data-ad-slot="7983117522"></ins><br>
<script><br />
     (adsbygoogle = window.adsbygoogle || []).push({});<br />
</script></p>
<p><img class="alignnone size-full wp-image-1495" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/sp3-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/sp3-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/sp3-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/sp3-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p><strong>Applications:</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/data-structure/307-range-sum-query-mutable/">花花酱 307. Range Sum Query &#8211; Mutable</a></li>
<li><a href="http://zxi.mytechroad.com/blog/difficulty/hard/315-count-of-smaller-numbers-after-self/">花花酱 315. Count of Smaller Numbers After Self</a></li>
</ul>
<p><strong>Implementation:</strong></p>
<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">class FenwickTree {    
public:
    FenwickTree(int n): sums_(n + 1, 0) {}
    
    void update(int i, int delta) {
        while (i &lt; sums_.size()) {
            sums_[i] += delta;
            i += lowbit(i);
        }
    }
    
    int query(int i) const {        
        int sum = 0;
        while (i &gt; 0) {
            sum += sums_[i];
            i -= lowbit(i);
        }
        return sum;
    }
private:
    static inline int lowbit(int x) { 
        return x &amp; (-x); 
    }
    vector&lt;int&gt; sums_;
};</pre>

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

<pre class="crayon-plain-tag">class FenwickTree {
    int sums_[];
    public FenwickTree(int n) {
        sums_ = new int[n + 1];
    }
    
    public void update(int i, int delta) {
        while (i &lt; sums_.length) {
            sums_[i] += delta;
            i += i &amp; -i;
        }
    }
    
    public int query(int i) {
        int sum = 0;
        while (i &gt; 0) {
            sum += sums_[i];
            i -= i &amp; -i;
        }
        return sum;
    }
}</pre>

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

<pre class="crayon-plain-tag">class FenwickTree:
    def __init__(self, n):
        self._sums = [0 for _ in range(n + 1)]
        
    def update(self, i, delta):
        while i &lt; len(self._sums):
            self._sums[i] += delta
            i += i &amp; -i
    
    def query(self, i):
        s = 0
        while i &gt; 0:
            s += self._sums[i]
            i -= i &amp; -i
        return s</pre>
</div></div>


<h2><strong>Applications</strong></h2>



<ul><li><a href="https://zxi.mytechroad.com/blog/data-structure/307-range-sum-query-mutable/">https://zxi.mytechroad.com/blog/data-structure/307-range-sum-query-mutable/</a></li><li><a href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-315-count-of-smaller-numbers-after-self/">https://zxi.mytechroad.com/blog/algorithms/array/leetcode-315-count-of-smaller-numbers-after-self/</a></li><li><a href="https://zxi.mytechroad.com/blog/simulation/leetcode-1409-queries-on-a-permutation-with-key/">https://zxi.mytechroad.com/blog/simulation/leetcode-1409-queries-on-a-permutation-with-key/</a></li></ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/sp/fenwick-tree-binary-indexed-tree-sp3/">花花酱 Fenwick Tree / Binary Indexed Tree / 树状数组 SP3</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/sp/fenwick-tree-binary-indexed-tree-sp3/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 315. Count of Smaller Numbers After Self</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-315-count-of-smaller-numbers-after-self/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-315-count-of-smaller-numbers-after-self/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 04 Jan 2018 05:59:12 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[binary indexed tree]]></category>
		<category><![CDATA[BST]]></category>
		<category><![CDATA[fenwick tree]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[reversed pairs]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1487</guid>

					<description><![CDATA[<p>题目大意：给你一个数组，对于数组中的每个元素，返回一共有多少在它之后的元素比它小。 Problem: You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-315-count-of-smaller-numbers-after-self/">花花酱 LeetCode 315. Count of Smaller Numbers After Self</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/2SVLYsq5W8M?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p>题目大意：给你一个数组，对于数组中的每个元素，返回一共有多少在它之后的元素比它小。</p>
<p><strong>Problem:</strong></p>
<p>You are given an integer array <i>nums</i> and you have to return a new <i>counts</i> array. The <i>counts</i> array has the property where <code>counts[i]</code> is the number of smaller elements to the right of <code>nums[i]</code>.</p>
<p><b>Example:</b></p><pre class="crayon-plain-tag">Given nums = [5, 2, 6, 1]

To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.</pre><p>Return the array <code>[2, 1, 1, 0]</code>.</p>
<p><strong>Idea:</strong></p>
<p>Fenwick Tree / Binary Indexed Tree</p>
<p>BST</p>
<p><img class="alignnone size-full wp-image-1515" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/315-ep149-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/315-ep149-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/315-ep149-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/315-ep149-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p><img class="alignnone size-full wp-image-1514" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/315-ep149-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/315-ep149-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/315-ep149-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/315-ep149-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p><img class="alignnone size-full wp-image-1513" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/315-ep149-3.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/315-ep149-3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/315-ep149-3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/315-ep149-3-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<h1><strong>Solution 1: Binary Indexed Tree (Fenwick Tree)</strong></h1>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Runnning time: 32 ms
// Time complexity: O(nlogn)
// Space complexity: O(k), k is the number unique elements
class FenwickTree {    
public:
    FenwickTree(int n): sums_(n + 1, 0) {}
    
    void update(int i, int delta) {
        while (i &lt; sums_.size()) {
            sums_[i] += delta;
            i += lowbit(i);
        }
    }
    
    int query(int i) const {        
        int sum = 0;
        while (i &gt; 0) {
            sum += sums_[i];
            i -= lowbit(i);
        }
        return sum;
    }
private:
    static inline int lowbit(int x) { return x &amp; (-x); }
    vector&lt;int&gt; sums_;
};

class Solution {
public:
    vector&lt;int&gt; countSmaller(vector&lt;int&gt;&amp; nums) {
        // Sort the unique numbers
        set&lt;int&gt; sorted(nums.begin(), nums.end());
        // Map the number to its rank
        unordered_map&lt;int, int&gt; ranks;
        int rank = 0;
        for (const int num : sorted)
            ranks[num] = ++rank;
        
        vector&lt;int&gt; ans;
        FenwickTree tree(ranks.size());
        // Scan the numbers in reversed order
        for (int i = nums.size() - 1; i &gt;= 0; --i) {
            // Chechk how many numbers are smaller than the current number.
            ans.push_back(tree.query(ranks[nums[i]] - 1));
            // Increse the count of the rank of current number.
            tree.update(ranks[nums[i]], 1);
        }
        
        std::reverse(ans.begin(), ans.end());
        return ans;
    }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 28 ms
class Solution {
  private static int lowbit(int x) { return x &amp; (-x); }
  
  class FenwickTree {    
    private int[] sums;    
    
    public FenwickTree(int n) {
      sums = new int[n + 1];
    }

    public void update(int i, int delta) {    
      while (i &lt; sums.length) {
          sums[i] += delta;
          i += lowbit(i);
      }
    }

    public int query(int i) {       
      int sum = 0;
      while (i &gt; 0) {
          sum += sums[i];
          i -= lowbit(i);
      }
      return sum;
    }    
  };
  
  public List&lt;Integer&gt; countSmaller(int[] nums) {
    int[] sorted = Arrays.copyOf(nums, nums.length);
    Arrays.sort(sorted);
    Map&lt;Integer, Integer&gt; ranks = new HashMap&lt;&gt;();
    int rank = 0;
    for (int i = 0; i &lt; sorted.length; ++i)
      if (i == 0 || sorted[i] != sorted[i - 1])
        ranks.put(sorted[i], ++rank);
    
    FenwickTree tree = new FenwickTree(ranks.size());
    List&lt;Integer&gt; ans = new ArrayList&lt;Integer&gt;();
    for (int i = nums.length - 1; i &gt;= 0; --i) {
      int sum = tree.query(ranks.get(nums[i]) - 1);      
      ans.add(tree.query(ranks.get(nums[i]) - 1));
      tree.update(ranks.get(nums[i]), 1);
    }
    
    Collections.reverse(ans);
    return ans;
  }
}</pre><p></div></div></p>
<h1><strong>Solution 2: BST</strong></h1>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 26 ms
struct BSTNode {
    int val;
    int count;
    int left_count;
    BSTNode* left;
    BSTNode* right;    
    BSTNode(int val): val(val), count(1), left_count(0), left{nullptr}, right{nullptr} {}
    ~BSTNode() { delete left; delete right; }
    int less_or_equal() const { return count + left_count; }
};
class Solution {
public:
    vector&lt;int&gt; countSmaller(vector&lt;int&gt;&amp; nums) {
        if (nums.empty()) return {};
        std::reverse(nums.begin(), nums.end());
        std::unique_ptr&lt;BSTNode&gt; root(new BSTNode(nums[0]));
        vector&lt;int&gt; ans{0};
        for (int i = 1; i &lt; nums.size(); ++i)
            ans.push_back(insert(root.get(), nums[i]));
        std::reverse(ans.begin(), ans.end());
        return ans;
    }
private:
    // Returns the number of elements smaller than val under root.
    int insert(BSTNode* root, int val) {
        if (root-&gt;val == val) {
            ++root-&gt;count;
            return root-&gt;left_count;
        } else if (val &lt; root-&gt;val) {
            ++root-&gt;left_count;
            if (root-&gt;left == nullptr) {
                root-&gt;left = new BSTNode(val);            
                return 0;
            } 
            return insert(root-&gt;left, val);
        } else  {
            if (root-&gt;right == nullptr) {
                root-&gt;right = new BSTNode(val);
                return root-&gt;less_or_equal();
            }
            return root-&gt;less_or_equal() + insert(root-&gt;right, val);
        }
    }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 10 ms
class Solution {
  class Node {
    int val;
    int count;
    int left_count;
    Node left;
    Node right;
    public Node(int val) { this.val = val; this.count = 1; }
    public int less_or_equal() { return count + left_count; }
  }
  
  public List&lt;Integer&gt; countSmaller(int[] nums) {
    List&lt;Integer&gt; ans = new ArrayList&lt;&gt;();
    if (nums.length == 0) return ans;
    int n = nums.length;
    Node root = new Node(nums[n - 1]);
    ans.add(0);
    for (int i = n - 2; i &gt;= 0; --i)
      ans.add(insert(root, nums[i]));
    Collections.reverse(ans);
    return ans;
  }
  
  private int insert(Node root, int val) {
    if (root.val == val) {
      ++root.count;
      return root.left_count;
    } else if (val &lt; root.val) {
      ++root.left_count;
      if (root.left == null) {
        root.left = new Node(val);            
        return 0;
      } 
      return insert(root.left, val);
    } else  {
      if (root.right == null) {
        root.right = new Node(val);
        return root.less_or_equal();
      }
      return root.less_or_equal() + insert(root.right, val);
    }
  }
}</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-315-count-of-smaller-numbers-after-self/">花花酱 LeetCode 315. Count of Smaller Numbers After Self</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-315-count-of-smaller-numbers-after-self/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
