
2025-11-01:数位和等于下标的最小下标。用go语言,给定一个整数数组 nums,找出最小的索引 i(索引从 0 开始),使得把 nums[i] 按位拆分后各位数字相加得到的和等于 i。如果不存在这样的索引,则返回 -1。
1 <= nums.length <= 100。
0 <= nums[i] <= 1000。
输入:nums = [1,3,2]。
输出:2。
解释:
nums[2] = 2,其数位和等于 2 ,与其下标 i = 2 相等。因此,输出为 2 。
题目来自力扣3550。
nums 作为输入min(len(nums), 28) 个元素[1,3,2],数组长度为 3,所以会检查所有 3 个元素i 和对应的元素 x:s = 0x 反复除以 10,每次取余数得到最低位数字s 中s 与当前索引 ii 作为结果总的时间复杂度:O(1)
总的额外空间复杂度:O(1)
package main
import (
"fmt"
)
func smallestIndex(nums []int)int {
for i, x := range nums[:min(len(nums), 28)] {
s := 0
for ; x > 0; x /= 10 {
s += x % 10
}
if s == i {
return i
}
}
return-1
}
func main() {
nums := []int{1, 3, 2}
result := smallestIndex(nums)
fmt.Println(result)
}

# -*-coding:utf-8-*-
defsmallest_index(nums):
for i inrange(min(len(nums), 28)):
x = nums[i]
s = 0
while x > 0:
s += x % 10
x //= 10
if s == i:
return i
return -1
if __name__ == "__main__":
nums = [1, 3, 2]
result = smallest_index(nums)
print(result)
我们相信人工智能为普通人提供了一种“增强工具”,并致力于分享全方位的AI知识。在这里,您可以找到最新的AI科普文章、工具评测、提升效率的秘籍以及行业洞察。 欢迎关注“福大大架构师每日一题”,发消息可获得面试资料,让AI助力您的未来发展。