LeetCode Solutions
315. Count of Smaller Numbers After Self
Time: $O(n\log n)$ Space: $O(n)$
class FenwickTree {
public:
FenwickTree(int n) : sums(n + 1) {}
void update(int i, int delta) {
while (i < sums.size()) {
sums[i] += delta;
i += lowbit(i);
}
}
int get(int i) const {
int sum = 0;
while (i > 0) {
sum += sums[i];
i -= lowbit(i);
}
return sum;
}
private:
vector<int> sums;
static inline int lowbit(int i) {
return i & -i;
}
};
class Solution {
public:
vector<int> countSmaller(vector<int>& nums) {
vector<int> ans(nums.size());
unordered_map<int, int> ranks;
getRanks(nums, ranks);
FenwickTree tree(ranks.size());
for (int i = nums.size() - 1; i >= 0; --i) {
const int num = nums[i];
ans[i] = tree.get(ranks[num] - 1);
tree.update(ranks[num], 1);
}
return ans;
}
private:
void getRanks(const vector<int>& nums, unordered_map<int, int>& ranks) {
set<int> sorted(begin(nums), end(nums));
int rank = 0;
for (const int num : sorted)
ranks[num] = ++rank;
}
};
class FenwickTree {
public FenwickTree(int n) {
sums = new int[n + 1];
}
public void update(int i, int delta) {
while (i < sums.length) {
sums[i] += delta;
i += lowbit(i);
}
}
public int get(int i) {
int sum = 0;
while (i > 0) {
sum += sums[i];
i -= lowbit(i);
}
return sum;
}
private int[] sums;
private static int lowbit(int i) {
return i & -i;
}
}
class Solution {
public List<Integer> countSmaller(int[] nums) {
List<Integer> ans = new ArrayList<>();
Map<Integer, Integer> ranks = new HashMap<>();
getRanks(nums, ranks);
FenwickTree tree = new FenwickTree(ranks.size());
for (int i = nums.length - 1; i >= 0; --i) {
final int num = nums[i];
ans.add(tree.get(ranks.get(num) - 1));
tree.update(ranks.get(num), 1);
}
Collections.reverse(ans);
return ans;
}
private void getRanks(int[] nums, Map<Integer, Integer> ranks) {
SortedSet<Integer> sorted = new TreeSet<>();
for (final int num : nums)
sorted.add(num);
int rank = 0;
for (Iterator<Integer> it = sorted.iterator(); it.hasNext();)
ranks.put(it.next(), ++rank);
}
}
class FenwickTree:
def __init__(self, n: int):
self.sums = [0] * (n + 1)
def update(self, i: int, delta: int) -> None:
while i < len(self.sums):
self.sums[i] += delta
i += self._lowbit(i)
def get(self, i: int) -> int:
summ = 0
while i > 0:
summ += self.sums[i]
i -= self._lowbit(i)
return summ
def _lowbit(self, i) -> int:
return i & -i
class Solution:
def countSmaller(self, nums: List[int]) -> List[int]:
ans = []
ranks = Counter()
self._getRanks(nums, ranks)
tree = FenwickTree(len(ranks))
for num in reversed(nums):
ans.append(tree.get(ranks[num] - 1))
tree.update(ranks[num], 1)
return ans[::-1]
def _getRanks(self, nums: List[int], ranks: Dict[int, int]) -> None:
rank = 0
for num in sorted(set(nums)):
rank += 1
ranks[num] = rank