【力扣每日一题】1365. 有多少小于当前数字的数字

雨点打透心脏的1/2处 2022-12-18 10:53 255阅读 0赞

1. 题目描述

在这里插入图片描述

2. 题目思路

  • 给定一个数组,让你返回每个数值数组中比他小的个数
  • 思路一:直接暴力,两次for循环,出结果
  • 思路二:快速排序,prev == -1 || data[i][0] != data[i - 1][0],如果当前的数值不等于前面的数值的话,说明不重复,进行ret[data[i][1]] = prev;
  • 思路三:桶排序,一遍循环放桶中,一遍循环求下前缀和,最后一遍得出结果注意:因为该题目指定了规定的数据区间

3. 题目代码

  1. public static int[] SmallerNumbersThanCurrent(int[] nums)
  2. {
  3. // 桶排
  4. int[] array = new int[101];
  5. for (int i = 0; i < nums.Length; i++)
  6. {
  7. array[nums[i]]++;
  8. }
  9. for (int i = 1; i < 101; i++)
  10. {
  11. array[i] = array[i] + array[i - 1];
  12. }
  13. int[] cnt = new int[nums.Length];
  14. for (int i = 0; i < nums.Length; i++)
  15. {
  16. if (nums[i] == 0)
  17. {
  18. cnt[i] = 0;
  19. }
  20. else
  21. {
  22. cnt[i] = array[nums[i] - 1];
  23. }
  24. }
  25. return cnt;
  26. }

发表评论

表情:
评论列表 (有 0 条评论,255人围观)

还没有评论,来说两句吧...

相关阅读