leetcode 3740. 三个相等元素之间的最小距离 I 简单

给你一个整数数组 nums

如果满足 nums[i] == nums[j] == nums[k],且 (i, j, k) 是 3 个 不同 下标,那么三元组 (i, j, k) 被称为 有效三元组

有效三元组距离 被定义为 abs(i - j) + abs(j - k) + abs(k - i),其中 abs(x) 表示 x绝对值

返回一个整数,表示 有效三元组最小 可能距离。如果不存在 有效三元组 ,返回 -1

示例 1:

输入: nums = 1,2,1,1,3

输出: 6

解释:

最小距离对应的有效三元组是 (0, 2, 3)

(0, 2, 3) 是一个有效三元组,因为 nums[0] == nums[2] == nums[3] == 1。它的距离为 abs(0 - 2) + abs(2 - 3) + abs(3 - 0) = 2 + 1 + 3 = 6

示例 2:

输入: nums = 1,1,2,3,2,1,2

输出: 8

解释:

最小距离对应的有效三元组是 (2, 4, 6)

(2, 4, 6) 是一个有效三元组,因为 nums[2] == nums[4] == nums[6] == 2。它的距离为 abs(2 - 4) + abs(4 - 6) + abs(6 - 2) = 2 + 2 + 4 = 8

示例 3:

输入: nums = 1

输出: -1

解释:

不存在有效三元组,因此答案为 -1。

提示:

  • 1 <= n == nums.length <= 100
  • 1 <= nums[i] <= n

分析:用一个 vector 记录每个数字出现的位置,当一个数次出现次数大于等于 3 时,计算最后三个出现位置的距离和即可。

cpp 复制代码
class Solution {
public:
    int minimumDistance(vector<int>& nums) {
        int n=nums.size(),ans=1000;
        vector<vector<int>>index(n+5);
        for(int i=0;i<n;++i)
        {
            index[nums[i]].push_back(i);
            if(index[nums[i]].size()>=3)
            {
                ans=min(ans,2*(index[nums[i]][index[nums[i]].size()-1]-index[nums[i]][index[nums[i]].size()-3]));
            }
        }
        return ans==1000?-1:ans;;
    }
};
相关推荐
203号居民10 小时前
LeetCode hot 100 —41. 缺失的第一个正数
数据结构·算法·leetcode
evans在进步13 小时前
LeetCode 322:零钱兑换——Java 动态规划详解
java·leetcode·动态规划
Tisfy15 小时前
LeetCode 3471.找出最大的几近缺失整数:三种情况判断
算法·leetcode·题解·分类讨论
青 春 记 忆18 小时前
LeetCode 121. 买卖股票的最佳时机|Python 解法详解
python·算法·leetcode
rannn_11119 小时前
【力扣hot100】二叉树专题
算法·leetcode·职场和发展
Navigator_Z20 小时前
LeetCode //C - 1203. Sort Items by Groups Respecting Dependencies
c语言·算法·leetcode
Scabbards_1 天前
面试Leetcode - Heap 堆
java·leetcode·面试
ValhallaCoder2 天前
Leetcode-hot100(2026.08.17)
python·算法·leetcode
青 春 记 忆2 天前
LeetCode 104. 二叉树的最大深度|Python 解法详解
python·算法·leetcode
evans在进步2 天前
LeetCode 198:打家劫舍——Java 动态规划详解
java·leetcode·动态规划