Leetcode 1365. How Many Numbers Are Smaller Than the Current Number
Given the array nums
, for each nums[i]
find out how many numbers in the array are smaller than it. That is, for each nums[i]
, you have to count the number of valid j
’s such that j != i
and nums[j] < nums[i]
. Return the answer in an array.
Input:
nums = [8, 1, 2, 2, 3]
Output:
[4, 0, 1, 1, 3]
Explanation:
nums[0]=8
there are four smaller numbers: 1, 2, 2, 3
.nums[1]=1
there are no smaller numbers.nums[2]=2
there is one smaller number: 1
. Note that the number occurs twice.nums[3]=2
there is also one smaller number: 1
.nums[4]=3
there are three smaller numbers: 1, 2, 2
.nums
array and sort this copy.Here is the implementation of the optimal approach:
#include <vector>
#include <algorithm>
#include <unordered_map>
std::vector<int> smallerNumbersThanCurrent(std::vector<int>& nums) {
// Create a sorted copy of nums
std::vector<int> sorted_nums(nums);
std::sort(sorted_nums.begin(), sorted_nums.end());
// Create a hash map to store the first occurrence index of each number
std::unordered_map<int, int> num_to_count;
for (int i = 0; i < sorted_nums.size(); i++) {
if (num_to_count.find(sorted_nums[i]) == num_to_count.end()) {
num_to_count[sorted_nums[i]] = i;
}
}
// Generate the result array using the hash map
std::vector<int> result(nums.size());
for (int i = 0; i < nums.size(); i++) {
result[i] = num_to_count[nums[i]];
}
return result;
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?