Mercury: Contains Duplicate III
harbor run -t elfsong/mercury-contains-duplicate-iiiharbor download elfsong/mercury-contains-duplicate-iiiYou are given an integer array nums and two integers indexDiff and valueDiff.
Find a pair of indices (i, j) such that:
i != j,
abs(i - j) <= indexDiff.
abs(nums[i] - nums[j]) <= valueDiff, and
Return true if such pair exists or false otherwise.
Example 1:
Input: nums = [1,2,3,1], indexDiff = 3, valueDiff = 0 Output: true Explanation: We can choose (i, j) = (0, 3). We satisfy the three conditions: i != j --> 0 != 3 abs(i - j) <= indexDiff --> abs(0 - 3) <= 3 abs(nums[i] - nums[j]) <= valueDiff --> abs(1 - 1) <= 0
Example 2:
Input: nums = [1,5,9,1,5,9], indexDiff = 2, valueDiff = 3 Output: false Explanation: After trying all the possible pairs (i, j), we cannot satisfy the three conditions, so we return false.
Constraints:
2 <= nums.length <= 10⁵
-10⁹ <= nums[i] <= 10⁹
1 <= indexDiff <= nums.length
0 <= valueDiff <= 10⁹
Implement Solution.containsNearbyAlmostDuplicate in /app/solution.py using Python 3.12.
Keep the supplied class and method signature. The file is the only submitted artifact.
The evaluator instantiates Solution and invokes this method with the problem's inputs;
do not read standard input or write a command-line program.
class Solution(object):
def containsNearbyAlmostDuplicate(self, nums, indexDiff, valueDiff):
"""
:type nums: List[int]
:type indexDiff: int
:type valueDiff: int
:rtype: bool
"""
The standard library, lctk 0.0.6 (LeetCode tree/list helpers), sortedcontainers 2.4.0, NumPy 2.4.3, SciPy 1.17.1, and six 1.17.0 are available. Standard LeetCode imports, including List, Optional, TreeNode and ListNode, are provided by the starter file.
Your solution must pass every hidden test. For a correct solution, the evaluator also measures CPU runtime over 128 repetitions per test using independent copies of the inputs, and compares it with passing reference solutions measured in the same environment. Aim for an efficient algorithm. Wrong solutions receive zero efficiency credit.