Give you an array `nums`, for each element `nums[i]`, please count the number of all numbers smaller than it in the array. In other words, for each `nums[i]` you have to calculate the number of valid `j`, where `j`

x1365. How many numbers are smaller than the current number

Give you an array nums. For each element in it nums[i], please count the number of all numbers smaller than it in the array.

In other words, for each of nums[i]you have to calculate the effective jnumber, which jmeet j != i and nums[j] < nums[i] .

The answer is returned as an array.

Example 1:

输入:nums = [8,1,2,2,3]
输出:[4,0,1,1,3]
解释: 
对于 nums[0]=8 存在四个比它小的数字:(1,2,2 和 3)。 
对于 nums[1]=1 不存在比它小的数字。
对于 nums[2]=2 存在一个比它小的数字:(1)。 
对于 nums[3]=2 存在一个比它小的数字:(1)。 
对于 nums[4]=3 存在三个比它小的数字:(1,2 和 2)。

Example 2:

输入:nums = [6,5,4,8]
输出:[2,1,0,3]

Example 3:

输入:nums = [7,7,7,7]
输出:[0,0,0,0]

prompt:

  • 2 <= nums.length <= 500
  • 0 <= nums[i] <= 100

I personally think of bucket sorting, which is troublesome and directly violent.

Code borrowing
class Solution {
public:
    vector<int> smallerNumbersThanCurrent(vector<int>& nums) {
        vector<int> cnt(101, 0);
        int n = nums.size();
        for (int i = 0; i < n; i++) {
            cnt[nums[i]]++;
        }
        for (int i = 1; i <= 100; i++) {//关键在这里,如果想要将该下标之前的数全部都加起来,那么可以使用累死循环;
            cnt[i] += cnt[i - 1];
        }
        vector<int> ret;
        for (int i = 0; i < n; i++) {
            ret.push_back(nums[i] == 0 ? 0 : cnt[nums[i] - 1]);
        }
        return ret;
    }
};

Guess you like

Origin blog.csdn.net/weixin_45929885/article/details/114085122