Skip to main content

存在重复元素-iii

Tips

题目类型: HashMap

相关题目:

题目

给你一个整数数组 nums 和两个整数 kt. 请你判断是否存在两个不同下标 ij, 使得 abs(nums[i] - nums[j]) <= t, 同时又满足 abs(i - j) <= k. 如果存在则返回 true, 不存在返回 false.

示例
输入: nums = [1, 2, 3, 1], k = 3, t = 0
输出: true
输入: nums = [1, 0, 1, 1], k = 1, t = 2
输出: true
输入: nums = [1, 5, 9, 1, 5, 9], k = 2, t = 3
输出: false

题解

这里是题解这里是题解这里是题解这里是题解这里是题解

/**
* @param {number[]} nums
* @param {number} indexDiff
* @param {number} valueDiff
* @return {boolean}
*/
var containsNearbyAlmostDuplicate = function (nums, indexDiff, valueDiff) {
const n = nums.length

for (let i = 0; i < n; i++) {
const maxJ = i + indexDiff
let j = maxJ >= n ? n - 1 : maxJ

while (i < j) {
const currIndexDiff = Math.abs(i - j)
const currValueDiff = Math.abs(nums[i] - nums[j])
if (currIndexDiff <= indexDiff && currValueDiff <= valueDiff) return true
j--
}
}

return false
}