You are viewing a single comment's thread. Return to all comments →
Typescipt sliding window
function closestNumbers(arr: number[]): number[] { arr.sort((a, b) => a - b); let windowStart = 0; let min = arr[1] - arr[0]; let result = [] as number[]; for (let windowEnd = 1; windowEnd < arr.length; windowEnd++) { const diff = arr[windowEnd] - arr[windowStart]; if (diff === min) { result.push(arr[windowStart]); result.push(arr[windowEnd]); windowStart++; continue; } if (diff < min) { min = diff; result = [arr[windowStart], arr[windowEnd]]; } windowStart++; } return result; }
Seems like cookies are disabled on this browser, please enable them to open this website
Closest Numbers
You are viewing a single comment's thread. Return to all comments →
Typescipt sliding window