Skip to content

Instantly share code, notes, and snippets.

@chmllr
Created June 20, 2015 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chmllr/a7cae317d76c9974662f to your computer and use it in GitHub Desktop.
Save chmllr/a7cae317d76c9974662f to your computer and use it in GitHub Desktop.
var containsNearbyAlmostDuplicate = function (nums, k, t) {
if (k < 1 || t < 0 || nums.length < 2) return false;
var B = {}, MIN = -1 * 2147483648;
for (var i = 0; i < nums.length; ++i) {
var N = nums[i] - MIN;
var bucket = Math.floor(N / t);
var list = B[bucket] || [];
var cands = list.concat(B[bucket - 1] || [], B[bucket + 1] || []);
for (var i = 0; i < cands.length; ++i) {
var x = cands[i];
if (Math.abs(x.val - N) <= t && Math.abs(x.pos - i) <= k) return true;
}
list.push({ val: N, pos: i });
B[bucket] = list;
if (i > k) {
var pos = i - k;
N = nums[pos] - MIN;
bucket = Math.floor(N / t);
B[bucket] = B[bucket].filter(function (x) { return x.pos != pos });
}
}
return false;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment