class Solution:
def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if abs(nums[i] - nums[j]) <= t and j - i <= k:
return True
return False
class Solution:
def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
for i in range(len(nums)):
for j in range(i + 1, min(len(nums), i + k + 1)):
if abs(nums[i] - nums[j]) <= t:
return True
return False
class Solution:
def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
bucket = dict()
if t < 0: return False
for i in range(len(nums)):
nth = nums[i] // (t + 1)
if nth in bucket:
return True
if nth - 1 in bucket and abs(nums[i] - bucket[nth - 1]) <= t:
return True
if nth + 1 in bucket and abs(nums[i] - bucket[nth + 1]) <= t:
return True
bucket[nth] = nums[i]
if i >= k: bucket.pop(nums[i - k] // (t + 1))
return False
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
if(t<0) return false;
//t+1可能会溢出,所以要+ 1LL
long long mod = t + 1LL;
unordered_map<long long,long long> buck;
for(int i=0;i<nums.size();i++)
{
long long nth = nums[i] / mod;
//可能nums[i]为负数,比如-4 / 5 以及 -4 / 5都等于0,所以负数要向下移动一位
if(nums[i] < 0) nth--;
//这里要用find 不能直接[],因为可能本身存储的数字就为0
if(buck.find(nth)!=buck.end())
return true;
else if(buck.find(nth-1)!=buck.end() && abs(nums[i] - buck[nth-1]) <= t)
return true;
else if(buck.find(nth+1)!=buck.end() && abs(nums[i] - buck[nth+1]) <= t)
return true;
buck[nth] = nums[i];
if(i >= k)
{
long long pos = nums[i - k] / mod;
if(nums[i - k] < 0) pos--;
buck.erase(pos);
}
}
return false;
}
};