From 3de94d7fd0b5b6671dab038236f04ad649e73e69 Mon Sep 17 00:00:00 2001 From: Bhuwanesh Nainwal <70212380+BhuwaneshNainwal@users.noreply.github.com> Date: Sun, 9 Oct 2022 08:40:47 +0530 Subject: [PATCH] Update Count of Smaller Numbers After Self.cpp --- Count of Smaller Numbers After Self.cpp | 56 +++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/Count of Smaller Numbers After Self.cpp b/Count of Smaller Numbers After Self.cpp index 49cbff34..58108ce8 100644 --- a/Count of Smaller Numbers After Self.cpp +++ b/Count of Smaller Numbers After Self.cpp @@ -1,4 +1,6 @@ + +/* Approach 1: Using merge-sort technique */ void merge(vector > &v,int l,int mid,int r,vector &ans){ int i=l,j=mid,k=0; vector > temp(r-l+1); @@ -46,3 +48,57 @@ class Solution { return ans; } }; + + + +/* Approach 2: Using Policy Based Data Structure technique */ +#include +#include +#include + +using namespace __gnu_pbds; +using namespace std; + + +typedef tree, rb_tree_tag, tree_order_statistics_node_update> pbds; + + +class Solution { +public: + + void myerase(pbds &t, int v){ + + int rank = t.order_of_key(v); + pbds::iterator it = t.find_by_order(rank); + t.erase(it); + } + vector countSmaller(vector& nums) { + + int n = nums.size(); + pbds st; + for(int i = n - 1 ; i >= 0 ; i--) + { + st.insert(nums[i]); + } + + vector count(n); + for(int i = 0 ; i < n ; i++) + { + + myerase(st, nums[i]); + + auto it = st.upper_bound(nums[i]); + if(it == st.end()) + count[i] = st.size(); + + else + count[i] = st.order_of_key(*it); + + if(count[i] < 0) + count[i] = 0; + } + + return count; + + } +};