LeetCode 题解工作台

数位和等于下标的最小下标

给你一个整数数组 nums 。 返回满足 nums[i] 的数位和(每一位数字相加求和)等于 i 的 最小 下标 i 。 如果不存在满足要求的下标,返回 -1 。 示例 1: 输入: nums = [1,3,2] 输出: 2 解释: nums[2] = 2 ,其数位和等于 2 ,与其下标 i = 2…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·数学

bolt

答案摘要

我们可以从下标 $i = 0$ 开始,遍历数组中的每个元素 ,计算 的数位和 。如果 $s = i$,则返回下标 。如果遍历完所有元素都没有找到满足条件的下标,则返回 -1。 时间复杂度 ,其中 是数组的长度。空间复杂度 ,只使用了常数级别的额外空间。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 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 <= 100
  • 0 <= nums[i] <= 1000
lightbulb

解题思路

方法一:枚举 + 数位和

我们可以从下标 i=0i = 0 开始,遍历数组中的每个元素 xx,计算 xx 的数位和 ss。如果 s=is = i,则返回下标 ii。如果遍历完所有元素都没有找到满足条件的下标,则返回 -1。

时间复杂度 o(n)o(n),其中 nn 是数组的长度。空间复杂度 o(1)o(1),只使用了常数级别的额外空间。

1
2
3
4
5
6
7
8
9
10
11
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

数位和等于下标的最小下标题解:数组·数学 | LeetCode #3550 简单