LeetCode 题解工作台
数位和等于下标的最小下标
给你一个整数数组 nums 。 返回满足 nums[i] 的数位和(每一位数字相加求和)等于 i 的 最小 下标 i 。 如果不存在满足要求的下标,返回 -1 。 示例 1: 输入: nums = [1,3,2] 输出: 2 解释: nums[2] = 2 ,其数位和等于 2 ,与其下标 i = 2…
2
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·数学
答案摘要
我们可以从下标 $i = 0$ 开始,遍历数组中的每个元素 ,计算 的数位和 。如果 $s = i$,则返回下标 。如果遍历完所有元素都没有找到满足条件的下标,则返回 -1。 时间复杂度 ,其中 是数组的长度。空间复杂度 ,只使用了常数级别的额外空间。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给你一个整数数组 nums 。
返回满足 nums[i] 的数位和(每一位数字相加求和)等于 i 的 最小 下标 i 。
如果不存在满足要求的下标,返回 -1 。
示例 1:
输入:nums = [1,3,2]
输出:2
解释:
nums[2] = 2,其数位和等于 2 ,与其下标i = 2相等。因此,输出为 2 。
示例 2:
输入:nums = [1,10,11]
输出:1
解释:
nums[1] = 10,其数位和等于1 + 0 = 1,与其下标i = 1相等。nums[2] = 11,其数位和等于是1 + 1 = 2,与其下标i = 2相等。- 由于下标 1 是满足要求的最小下标,输出为 1 。
示例 3:
输入:nums = [1,2,3]
输出:-1
解释:
- 由于不存在满足要求的下标,输出为 -1 。
提示:
1 <= nums.length <= 1000 <= nums[i] <= 1000
解题思路
方法一:枚举 + 数位和
我们可以从下标 开始,遍历数组中的每个元素 ,计算 的数位和 。如果 ,则返回下标 。如果遍历完所有元素都没有找到满足条件的下标,则返回 -1。
时间复杂度 ,其中 是数组的长度。空间复杂度 ,只使用了常数级别的额外空间。
class Solution:
def smallestIndex(self, nums: List[int]) -> int:
for i, x in enumerate(nums):
s = 0
while x:
s += x % 10
x //= 10
if s == i:
return i
return -1
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate efficiently calculates the sum of digits for each element.
- question_mark
The candidate checks for matching index and sum of digits correctly.
- question_mark
The candidate can optimize the digit sum calculation for large numbers.
常见陷阱
外企场景- error
Not calculating the sum of digits correctly.
- error
Failing to return the smallest matching index when there are multiple matches.
- error
Not handling edge cases like when no match exists or the array contains very large numbers.
进阶变体
外企场景- arrow_right_alt
Try using a mathematical formula for digit sum calculation instead of iteration.
- arrow_right_alt
Optimize for very large input arrays.
- arrow_right_alt
Consider edge cases like when the number at the index is a single digit.