LeetCode 1365 How many numbers are smaller than the current number

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 must calculate the number of valid j, where j satisfies j != i and nums[j] <nums[i].

The answer is returned as an array.

Example 1:

Input: nums = [8,1,2,2,3]
Output: [4,0,1,1,3]
Explanation:
For nums[0]=8 there are four numbers smaller than it: (1, 2 , 2 and 3).
For nums[1]=1 there is no smaller number than it.
For nums[2]=2 there is a smaller number: (1).
For nums[3]=2 there is a smaller number: (1).
For nums[4]=3, there are three smaller numbers: (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]

prompt:

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

Problem-solving idea:
I believe that everyone knows what method to use when you see the prompt. The range is only 100. It is better to use bucket sorting. First, use bucket sorting to calculate the number of each occurrence, and then traverse the buckets and count to a certain position. The number smaller than the current number at this position is the number counted to this position, the code is as follows:

class Solution {
    
    
public:
    vector<int> smallerNumbersThanCurrent(vector<int>& nums) {
    
    
        int arr[101];
        memset(arr, 0, sizeof(arr));
        // 初始化计数桶
        for (auto i : nums) {
    
    
            arr[i] ++;
        }
        // 累加处理计数桶,使得 arr[i] 表示比 i 小的数字的个数
        int cnt = 0;
        for (int i = 0; i <= 100; i ++) {
    
    
            int temp = arr[i];
            arr[i] = cnt;
            cnt += temp;
        }
        vector<int> ret;
        // 遍历 nums,取出对应桶 arr[i] 里的结果即可
        for (int i : nums) {
    
    
            ret.push_back(arr[i]);
        }
        return ret;
    }
};

Guess you like

Origin blog.csdn.net/HERODING23/article/details/109282473