[LeetCode] 1365. How many numbers are smaller than the current number (C++)

1 topic description

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.

2 Example description

2.1 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).

2.2 Example 2

Input: nums = [6,5,4,8]
Output: [2,1,0,3]

2.3 Example 3

Input: nums = [7,7,7,7]
Output: [0,0,0,0]

3 Problem solving tips

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

4 Detailed source code (C++)

class Solution {
    
    
public:
    vector<int> smallerNumbersThanCurrent(vector<int>& nums) {
    
    
        vector<int> res;
        int n = 0 ;
        for (int i = 0 ; i < nums.size() ; i ++)
        {
    
    
            for(int j = 0 ; j < nums.size() ; j ++)
            {
    
    
                if (nums[i] > nums[j])
                {
    
    
                    n ++;
                }
            }
            res.push_back(n);
            n = 0;
        }
        return res;
    }
};

Guess you like

Origin blog.csdn.net/Gyangxixi/article/details/114001379