1365. How many numbers are less than the current number ●

1365. How many numbers are less than the current number ●

describe

Given 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 compute the number of valid js such that j != i and nums[j] < nums[i].

Return the answer as an array.

example

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 number smaller than it.
For nums[2]=2 there exists a smaller number: (1).
For nums[3]=2 there exists a smaller number: (1).
For nums[4]=3 there are three smaller numbers: (1, 2 and 2).

answer

1. Violence

For each number, traverse and count the number of elements less than the number once.

2. Sort

After sorting the array from small to large, the leftmost subscript of the (repeated) element is the number of numbers smaller than the element ;

To do this, we copy a nums array vec, and sort it ,

Then, from the back to the front , update the subscript value corresponding to the current number to ensure that the subscript of the last updated number is the leftmost subscript value in the repeated element value ,

Then traverse the original array nums, and the value corresponding to cnts is the number of smaller numbers .

insert image description here

class Solution {
    
    
public:
    vector<int> smallerNumbersThanCurrent(vector<int>& nums) {
    
    
        int cnts[101] = {
    
    0};
        int n = nums.size();
        vector<int> vec = nums;
        sort(vec.begin(), vec.end());
        for(int i = n-1; i >= 0; --i) cnts[vec[i]] = i;
        for(int i = 0; i < n; ++i){
    
    
            vec[i] = cnts[nums[i]];
        }
        return vec;
    }
};

3. Count - prefix and

The element value range is within 100, so you can create a counting array for statistics, and get the prefix sum, cnts[i] indicates the number of <= i in the array, and finally traverse the original array to get the corresponding answer cnts[nums[i]- 1].

class Solution {
    
    
public:
    vector<int> smallerNumbersThanCurrent(vector<int>& nums) {
    
    
        int cnts[101] = {
    
    0};
        vector<int> ret(nums.size(), 0);
        for(int num : nums) ++cnts[num];		// 计数
        for(int i = 1; i <= 100; ++i){
    
    
            cnts[i] += cnts[i-1];				// 前缀和,cnts[i] 表示数组中 <= i 的个数
        }
        for(int i = 0; i < nums.size(); ++i){
    
    
            ret[i] = nums[i] >= 1? cnts[nums[i]-1] : 0;		// 小于 nums[i] 的个数为cnts[nums[i]-1]
        }
        return ret;
    }
};

Guess you like

Origin blog.csdn.net/qq_19887221/article/details/127061433