
题目描述
给你一个只包含 0、1 和 2 的整数数组 nums。
如果 nums[i] == 1 且 nums[j] == 2,则称下标对 (i, j) 为 有效 的。
请返回所有有效下标对中 i 和 j 之间的 最小 绝对差。如果不存在有效下标对,则返回 -1。
下标 i 和 j 之间的绝对差定义为 abs(i - j)。
示例 1:
输入: nums = [1,0,0,2,0,1]
输出: 2
解释:
有效下标对有:
- (0, 3),其绝对差为
abs(0 - 3) = 3。 - (5, 3),其绝对差为
abs(5 - 3) = 2。
因此,结果是 2。
示例 2:
输入: nums = [1,0,1,0]
输出: -1
解释:
数组中不存在有效下标对,因此结果是 -1。
提示:
1 <= nums.length <= 100 0 <= nums[i] <= 2
解法
方法一:一次遍历
我们用一个长度为 \(3\) 的数组 \(\textit{last}\) 来记录数字 \(0\), \(1\) 和 \(2\) 最后一次出现的下标。初始时 \(\textit{last} = [-(n+1), -(n+1), -(n+1)]\)。我们遍历数组 \(\textit{nums}\),对于当前遍历到的数字 \(x\),如果 \(x\) 不等于 \(0\),则更新答案 \(\textit{ans} = \min(\textit{ans}, i - \textit{last}[3 - x])\),其中 \(i\) 是当前遍历到的数字 \(x\) 的下标。然后更新 \(\textit{last}[x] = i\)。
遍历结束后,如果 \(\textit{ans}\) 大于数组 \(\textit{nums}\) 的长度,则说明不存在有效下标对,返回 -1;否则返回 \(\textit{ans}\)。
时间复杂度 \(O(n)\),其中 \(n\) 是数组 \(\textit{nums}\) 的长度。空间复杂度 \(O(1)\)。
| class Solution:
def minAbsoluteDifference(self, nums: list[int]) -> int:
n = len(nums)
ans = n + 1
last = [-inf] * 3
for i, x in enumerate(nums):
if x:
ans = min(ans, i - last[3 - x])
last[x] = i
return -1 if ans > n else ans
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 | class Solution {
public int minAbsoluteDifference(int[] nums) {
int n = nums.length;
int ans = n + 1;
int[] last = new int[3];
Arrays.fill(last, -(n + 1));
for (int i = 0; i < n; ++i) {
int x = nums[i];
if (x != 0) {
ans = Math.min(ans, i - last[3 - x]);
last[x] = i;
}
}
return ans > n ? -1 : ans;
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 | class Solution {
public:
int minAbsoluteDifference(vector<int>& nums) {
int n = nums.size();
int ans = n + 1;
vector<int> last(3, -(n + 1));
for (int i = 0; i < n; ++i) {
int x = nums[i];
if (x != 0) {
ans = min(ans, i - last[3 - x]);
last[x] = i;
}
}
return ans > n ? -1 : ans;
}
};
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 | func minAbsoluteDifference(nums []int) int {
n := len(nums)
ans := n + 1
last := []int{-ans, -ans, -ans}
for i, x := range nums {
if x != 0 {
ans = min(ans, i-last[3-x])
last[x] = i
}
}
if ans > n {
return -1
}
return ans
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 | function minAbsoluteDifference(nums: number[]): number {
const n = nums.length;
let ans = n + 1;
const last = Array(3).fill(-ans);
for (let i = 0; i < n; ++i) {
const x = nums[i];
if (x) {
ans = Math.min(ans, i - last[3 - x]);
last[x] = i;
}
}
return ans > n ? -1 : ans;
}
|