배열 요소값 보다 작은 값을 가진 요소의 갯수를 구하라.
Input: nums = [8,1,2,2,3]
Output: [4,0,1,1,3]
Explanation:
For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3).
For nums[1]=1 does not exist any smaller number than it.
For nums[2]=2 there exist one smaller number than it (1).
For nums[3]=2 there exist one smaller number than it (1).
For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).
class Solution {
public:
vector<int> smallerNumbersThanCurrent(vector<int>& nums) {
unordered_map<int, int> table; // nums[i], num of nums[i]
for (int i = 0; i < nums.size(); i++) {
table[nums[i]]++;
}
int nr_smaller = 0; // accumulate num of smaller one
for (int i = 0; i < 101; i++) {
if (table.find(i) != table.end()) {
int tmp = table[i];
table[i] = nr_smaller;
nr_smaller = nr_smaller + tmp; // update nr_smaller
}
}
for (int i = 0; i < nums.size(); i++) {
nums[i] = table[nums[i]];
}
return nums;
}
};