LeetCode 2057: Smallest Index With Equal Value (Index Mod 10 Match Check)
LeetCode 2057ArraySimulationToday we solve LeetCode 2057 - Smallest Index With Equal Value.
Source: https://leetcode.com/problems/smallest-index-with-equal-value/
English
Problem Summary
Given an integer array nums, return the smallest index i such that i % 10 == nums[i]. If no such index exists, return -1.
Key Insight
The condition only depends on the current index and value. So we can scan left to right and return immediately on the first match.
Algorithm
- Iterate i from 0 to n - 1.
- If i % 10 == nums[i], return i.
- If loop ends without match, return -1.
Complexity Analysis
Let n be the array length.
Time: O(n).
Space: O(1).
Common Pitfalls
- Returning the value instead of index.
- Forgetting modulo 10 and directly comparing i == nums[i].
- Not returning the first valid index (smallest index requirement).
Reference Implementations (Java / Go / C++ / Python / JavaScript)
class Solution {
public int smallestEqual(int[] nums) {
for (int i = 0; i < nums.length; i++) {
if (i % 10 == nums[i]) {
return i;
}
}
return -1;
}
}func smallestEqual(nums []int) int {
for i, v := range nums {
if i%10 == v {
return i
}
}
return -1
}class Solution {
public:
int smallestEqual(vector<int>& nums) {
for (int i = 0; i < (int)nums.size(); i++) {
if (i % 10 == nums[i]) {
return i;
}
}
return -1;
}
};class Solution:
def smallestEqual(self, nums: List[int]) -> int:
for i, v in enumerate(nums):
if i % 10 == v:
return i
return -1var smallestEqual = function(nums) {
for (let i = 0; i < nums.length; i++) {
if (i % 10 === nums[i]) {
return i;
}
}
return -1;
};中文
题目概述
给定整数数组 nums,找到最小下标 i,满足 i % 10 == nums[i]。若不存在则返回 -1。
核心思路
判断条件只依赖当前位置,所以线性扫描即可。第一次命中就直接返回,天然满足“最小下标”。
算法步骤
- 从 i = 0 遍历到 n - 1。
- 若 i % 10 == nums[i],返回 i。
- 遍历结束仍未命中,返回 -1。
复杂度分析
设数组长度为 n。
时间复杂度:O(n)。
空间复杂度:O(1)。
常见陷阱
- 把答案写成返回 nums[i] 而不是返回下标 i。
- 忘记取模,误写成 i == nums[i]。
- 没有在首次命中时返回,导致不满足最小下标要求。
多语言参考实现(Java / Go / C++ / Python / JavaScript)
class Solution {
public int smallestEqual(int[] nums) {
for (int i = 0; i < nums.length; i++) {
if (i % 10 == nums[i]) {
return i;
}
}
return -1;
}
}func smallestEqual(nums []int) int {
for i, v := range nums {
if i%10 == v {
return i
}
}
return -1
}class Solution {
public:
int smallestEqual(vector<int>& nums) {
for (int i = 0; i < (int)nums.size(); i++) {
if (i % 10 == nums[i]) {
return i;
}
}
return -1;
}
};class Solution:
def smallestEqual(self, nums: List[int]) -> int:
for i, v in enumerate(nums):
if i % 10 == v:
return i
return -1var smallestEqual = function(nums) {
for (let i = 0; i < nums.length; i++) {
if (i % 10 === nums[i]) {
return i;
}
}
return -1;
};
Comments