跳转至

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

题目描述

给你一个整数数组 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

解法

方法一:枚举 + 数位和

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

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
    public int smallestIndex(int[] nums) {
        for (int i = 0; i < nums.length; ++i) {
            int s = 0;
            while (nums[i] != 0) {
                s += nums[i] % 10;
                nums[i] /= 10;
            }
            if (s == i) {
                return i;
            }
        }
        return -1;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
public:
    int smallestIndex(vector<int>& nums) {
        for (int i = 0; i < nums.size(); ++i) {
            int s = 0;
            while (nums[i]) {
                s += nums[i] % 10;
                nums[i] /= 10;
            }
            if (s == i) {
                return i;
            }
        }
        return -1;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
func smallestIndex(nums []int) int {
    for i, x := range nums {
        s := 0
        for ; x > 0; x /= 10 {
            s += x % 10
        }
        if s == i {
            return i
        }
    }
    return -1
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
function smallestIndex(nums: number[]): number {
    for (let i = 0; i < nums.length; ++i) {
        let s = 0;
        for (; nums[i] > 0; nums[i] = Math.floor(nums[i] / 10)) {
            s += nums[i] % 10;
        }
        if (s === i) {
            return i;
        }
    }
    return -1;
}

评论