数组中两个重复数字之间的距离 (JavaScript)
我们需要编写一个 JavaScript 函数,它接收一个数字数组,该数组中至少包含一对重复数字。
我们的函数应返回数组中所有重复数字对之间的距离。
代码如下 −
const arr = [2, 3, 4, 2, 5, 4, 1, 3];
const findDistance = arr => {
var map = {}, res = {};
arr.forEach((el, ind) => {
map[el] = map[el] || [];
map[el].push(ind);
});
Object.keys(map).forEach(el => {
if (map[el].length > 1) {
res[el] = Math.min.apply(null, map[el].reduce((acc, val, ind, arr) => {
ind && acc.push(val - arr[ind - 1]);
return acc;
}, []));
};
});
return res;
}
console.log(findDistance(arr));以下是在控制台上的输出 −
{ '2': 3, '3': 6, '4': 3 }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP