Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j]is at most t and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3, t = 0
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1, t = 2
Output: true
Example 3:
Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false
Python's priority queue heapq is implemented via list, not like C++ or JAVA via Balanced BST. So heapq can not search range, like searching for the smallest node larger than target value (BST successor).
Below is a way to implement a not balanced BST to support that kind of requirement. [Not accepted yet]
classSolution(object):defcontainsNearbyAlmostDuplicate(self,nums,k,t):""" :type nums: List[int] :type k: int :type t: int :rtype: bool """if k <=0or t <0ornot nums:returnFalse priorityQ =PriorityQ([])for i inrange(len(nums)): candidate = priorityQ.successor(nums[i] - t)return nums[i]- t, candidateif candidate and candidate.val <= nums[i]+ t:returnTrue# if i >= k - 1: # This is not k distance, this is k - 1 distance# priorityQ.delete(nums[i - k + 1])if i >= k: priorityQ.delete(nums[i - k]) priorityQ.insert(nums[i])returnFalseclassTreeNode(object):def__init__(self,val): self.left =None self.right =None self.val = valclassPriorityQ(object):def__init__(self,nums):ifnot nums: self.root =Noneelse: self.root =TreeNode(nums[0])iflen(nums)>1:for i inrange(1, len(nums)): self.insert(nums[i])definsert(self,val):ifnot self.root: self.root =TreeNode(val)else: self._insert(self.root, val)defsuccessor(self,val):ifnot self.root:returnNonereturn self._successor(self.root, val, None)defdelete(self,val): self._delete(self.root, val)def_insert(self,root,val):ifnot root:returnTreeNode(val)if val < root.val: root.left = self._insert(root.left, val)else: root.right = self._insert(root.right, val)return rootdef_successor(self,root,val,successor):ifnot root:return successorif val < root.val:return self._successor(root.left, val, root)else:return self._successor(root.right, val, successor)def_delete(self,root,val):ifnot root:returnNoneif val < root.val: root.left = self._delete(root.left, val)return rootelif val > root.val: root.right = self._delete(root.right, val)return rootelse:ifnot root.left andnot root.right:returnNoneelifnot root.left:return root.rightelifnot root.right:return root.leftelse: successorInRightChild = self._successor(root, root.val, None) root.val = successorInRightChild.val root.right = self._delete(root.right, successorInRightChild.val)return root