1365. 有多少小於當前數字的數字
給你一個數組 nums
,對於其中每個元素 nums[i]
,請你統計數組中比它小的所有數字的數目。
換而言之,對於每個 nums[i]
你必須計算出有效的 j
的數量,其中 j
滿足 j != i
且 nums[j] < nums[i]
。
以數組形式返回答案。
示例 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)。
示例 2:
輸入:nums = [6,5,4,8]
輸出:[2,1,0,3]
示例 3:
輸入:nums = [7,7,7,7]
輸出:[0,0,0,0]
提示:
2 <= nums.length <= 500
0 <= nums[i] <= 100
解題思路
0 <= nums[i] <= 100
,取值範圍窄,常見的利用桶排序可以簡化的題目類型之一。
- 需要一個計數數組
count
,統計1~100
不同位置上分別存在多少個在nums
數組中對應的值。 - 需要一個求和數組
sum
,sum[k]
的值代表有sum[k]
個nums
數組中的值屬於0~k
範圍內。 - 求解有多少個值小於
nums[i]
,就是統計0~num[k]
存在多少個nums
數組中的值並減去等於nums[i]
的值,即count[nums[i]]
。
代碼(C語言)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define MAXN 1010
int* smallerNumbersThanCurrent(int* nums, int numsSize, int* returnSize){
const int maxn = 110;
int count[maxn],sum[maxn],i=0;
memset(count,0,sizeof(int)*maxn);
memset(sum,0,sizeof(int)*maxn);
for(i=0;i<numsSize;i++)
{
count[nums[i]]++;
}
sum[0] = count[0];
for(i =1;i<maxn;i++)
{
sum[i] = sum[i-1] + count[i];
}
*returnSize = numsSize;
int *res = (int *)malloc(sizeof(int)*numsSize);
for(i=0;i<numsSize;i++)
{
res[i] = sum[nums[i]]-count[nums[i]];
}
return res;
}
int main()
{
int a[] = {5,0,10,0,10,6};
int rsize = 0;
int *b = smallerNumbersThanCurrent(a,6,&rsize);
int i = 0;
for(i=0;i<rsize;i++)
{
printf("%d%c",b[i],i==rsize-1?'\n':' ');
}
}