LeetCode 题解工作台

值相等的最小索引

给你一个下标从 0 开始的整数数组 nums ,返回 nums 中满足 i mod 10 == nums[i] 的最小下标 i ;如果不存在这样的下标,返回 -1 。 x mod y 表示 x 除以 y 的 余数 。 示例 1: 输入: nums = [0,1,2] 输出: 0 解释: i=0: 0…

category

1

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·driven

bolt

答案摘要

我们直接遍历数组,对于每个下标 ,我们判断是否满足 $i \bmod 10 = \textit{nums}[i]$,如果满足则返回当前下标 。 如果遍历完数组都没有找到满足条件的下标,则返回 。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 0 开始的整数数组 nums ,返回 nums 中满足 i mod 10 == nums[i] 的最小下标 i ;如果不存在这样的下标,返回 -1

x mod y 表示 x 除以 y余数

 

示例 1:

输入:nums = [0,1,2]
输出:0
解释:
i=0: 0 mod 10 = 0 == nums[0].
i=1: 1 mod 10 = 1 == nums[1].
i=2: 2 mod 10 = 2 == nums[2].
所有下标都满足 i mod 10 == nums[i] ,所以返回最小下标 0

示例 2:

输入:nums = [4,3,2,1]
输出:2
解释:
i=0: 0 mod 10 = 0 != nums[0].
i=1: 1 mod 10 = 1 != nums[1].
i=2: 2 mod 10 = 2 == nums[2].
i=3: 3 mod 10 = 3 != nums[3].
2 唯一一个满足 i mod 10 == nums[i] 的下标

示例 3:

输入:nums = [1,2,3,4,5,6,7,8,9,0]
输出:-1
解释:不存在满足 i mod 10 == nums[i] 的下标

示例 4:

输入:nums = [2,1,3,5,2]
输出:1
解释:1 是唯一一个满足 i mod 10 == nums[i] 的下标

 

提示:

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 9
lightbulb

解题思路

方法一:遍历

我们直接遍历数组,对于每个下标 ii,我们判断是否满足 imod10=nums[i]i \bmod 10 = \textit{nums}[i],如果满足则返回当前下标 ii

如果遍历完数组都没有找到满足条件的下标,则返回 1-1

时间复杂度 O(n)O(n),其中 nn 是数组的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
class Solution:
    def smallestEqual(self, nums: List[int]) -> int:
        for i, x in enumerate(nums):
            if i % 10 == x:
                return i
        return -1
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Check the candidate's approach to early exits when a solution is found.

  • question_mark

    Assess how they handle edge cases like no valid index or a very small array.

  • question_mark

    Evaluate their understanding of the modulo operation and how it can be applied efficiently.

warning

常见陷阱

外企场景
  • error

    Overlooking the possibility of no valid index and returning incorrect results.

  • error

    Not returning the smallest valid index when multiple indices satisfy the condition.

  • error

    Confusing the modulo operation and how it works with non-zero divisors.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Change the condition to `i mod k == nums[i]` where k is a parameter.

  • arrow_right_alt

    Allow negative numbers in the array and modify the solution accordingly.

  • arrow_right_alt

    Limit the size of the array to a specific value and optimize the approach.

help

常见问题

外企场景

值相等的最小索引题解:数组·driven | LeetCode #2057 简单