Description
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.
Example 1:
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).
Example 2:
Input: nums = [6,5,4,8]
Output: [2,1,0,3]
Example 3:
Input: nums = [7,7,7,7]
Output: [0,0,0,0]
Constraints:
2 <= nums.length <= 500
0 <= nums[i] <= 100
Analyse
输入一个数组nums
,返回一个数组result
,数组中的result[i]
代表nums
中比nums[i]
小的元素个数
方法一
先对nums
进行排序,排序后的下标就是比nums[i]
小的元素个数,存到map里,但如果数组有重复的元素就会出错,所以禁止对map中的数据更新
vector<int> smallerNumbersThanCurrent(vector<int>& nums) {
vector<int> result(nums); // 备份nums
sort(nums.begin(), nums.end());
map<int, int> rankMap;
int len = nums.size();
for (int i = 0; i < len; i++) {
if (rankMap.find(nums[i]) == rankMap.end()) { // 仅当首次赋值时允许
rankMap[nums[i]] = i;
}
}
for (int j = 0; j < result.size(); j++) {
result[j] = rankMap[result[j]];
}
return result;
}
方法二
LeetCode上还有以一种做法,考虑到0 <= nums[i] <= 100
,可以用一个长度为101的数组存储 0-100出现的次数,比nums[i]小的元素的出现次数就是 nums[0] + nums[1] + ...... + nums[i-1]
vector<int> smallerNumbersThanCurrent(vector<int>& nums) {
vector<int> bitmap(101, 0); // 记录0-100出现次数
vector<int> result(nums.size(), 0);
for(int i : nums) {
++bitmap[i];
}
for(int i = 1; i < 101; i++) { // bitmap[i]现在为比i小的元素出现次数
bitmap[i] += bitmap[i-1];
}
for(int i = 0; i < nums.size(); ++i) {
result[i] = (nums[i] == 0) ? 0 : bitmap[nums[i] - 1];
}
return result;
}