LeetCode 题解工作台
有多少小于当前数字的数字
给你一个数组 nums ,对于其中每个元素 nums[i] ,请你统计数组中比它小的所有数字的数目。 换而言之,对于每个 nums[i] 你必须计算出有效的 j 的数量,其中 j 满足 j != i 且 nums[j] 。 以数组形式返回答案。 示例 1: 输入: nums = [8,1,2,2,3…
4
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们可以将数组 复制一份,记为 ,然后对 进行升序排序。 接下来,对于 中的每个元素 ,我们可以通过二分查找的方法找到第一个大于等于 的元素的下标 ,那么 就是比 小的元素的个数,我们将 存入答案数组中即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个数组 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 <= 5000 <= nums[i] <= 100
解题思路
方法一:排序 + 二分查找
我们可以将数组 复制一份,记为 ,然后对 进行升序排序。
接下来,对于 中的每个元素 ,我们可以通过二分查找的方法找到第一个大于等于 的元素的下标 ,那么 就是比 小的元素的个数,我们将 存入答案数组中即可。
时间复杂度 ,空间复杂度 。其中 是数组 的长度。
class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
arr = sorted(nums)
return [bisect_left(arr, x) for x in nums]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The problem tests the candidate's ability to optimize brute-force solutions using sorting or hashing techniques.
- question_mark
Watch for the candidate's approach to handling larger inputs efficiently, such as using sorting or hash tables.
- question_mark
The problem is an opportunity to assess familiarity with array manipulation and counting methods.
常见陷阱
外企场景- error
Overcomplicating the problem by attempting to use complex algorithms when a simpler sorting approach is enough.
- error
Failing to account for array elements with equal values, which should all have the same smaller count.
- error
Neglecting to optimize the brute force approach, which can lead to performance issues on larger datasets.
进阶变体
外企场景- arrow_right_alt
Modifying the array by adding or removing elements and checking if the solution adapts correctly.
- arrow_right_alt
Handling edge cases where all elements are the same, requiring the program to output an array of zeros.
- arrow_right_alt
Implementing the solution without sorting, using a hash map or frequency counter to reduce the time complexity.