Skip to content

Instantly share code, notes, and snippets.

@mrboli
Created April 16, 2020 19:47
Show Gist options
  • Save mrboli/1e0f927e572c0acfbe1854953c29d29f to your computer and use it in GitHub Desktop.
Save mrboli/1e0f927e572c0acfbe1854953c29d29f to your computer and use it in GitHub Desktop.
K Closest Points [WIP]
let distanceMemo = new Map();
var kClosest = function(points, K) {
// Choose pivot
// pseudo sort all items around pivot
// Get new partition position
// If K is larger, do again with a pivot in smaller section
// vice versa
let left = 0;
let right = points.length - 1;
let pivot, lastPivot;
let partitionIndex;
let targetIndex = K - 1;
let checkedPartitions = {};
console.log(points.map((point, i) => distance(i)))
while (partitionIndex !== targetIndex) { // left <= right &&
if (left >= right) console.log('there was a problem, left > right');
pivot = Math.floor((left + right) / 2);
partitionIndex = partition(pivot, left, right);
if (partitionIndex > targetIndex) {
right = partitionIndex - 1;
} else if (partitionIndex < targetIndex) {
left = partitionIndex + 1;
}
console.log(pivot, 'after partition:', JSON.stringify(points));
}
return points.slice(0, K);
function partition (pivot, left, right) {
const pivotVal = distance(pivot);
while (left <= right) {
while (distance(left) < pivotVal) {
left++;
}
while (distance(right) > pivotVal) {
right--;
}
if (distance(left) === distance(right)) return left;
// Swap points if still valid
if (left < right) {
swap(left, right);
left++;
right--;
}
}
swap(pivot, right);
return left;
}
function swap (left, right) {
const temp = points[left];
points[left] = points[right];
points[right] = temp;
}
function distance (index) {
const point = points[index];
const key = `${point[0]}${point[1]}`;
if (distanceMemo.has(key)) return distanceMemo.get(key);
const distance = point[0] ** 2 + point[1] ** 2;
distanceMemo.set(key, distance);
return distance;
}
};
@mrboli
Copy link
Author

mrboli commented Apr 16, 2020

Not working yet. Problem around pivot/partition scheme.

Currently using middle of left/right as new pivot based on last partition.
Somehow missing some values at end of the array.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment