2019年12月21日
找出数组中重复的数字
给定一个长度为 n 的整数数组 nums,数组中所有的数字都在 0∼n−1 的范围内。
数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。
请找出数组中任意一个重复的数字。
注意:如果某些数字不在 0∼n−1 的范围内,或数组中不包含重复数字,则返回 -1;
样例
给定 nums = [2, 3, 5, 4, 3, 2, 6, 7]。
返回 2 或 3。
ES6版
// const nums = [2, 3, 5, 4, 3, 2, 6, 7];
const nums = [];
const duplicateInArray = function (nums) {
nums.sort((a, b) => a - b); // 对数组进行预处理
const len = nums.length;
const repeatArr = [];
if (len === 0 || nums[len - 1] > len - 1 || nums[0] < 0) { // 处理特殊情况,某些数字不在 0∼n−1 的范围内,则返回 -1
return -1;
}
nums.reduce((temp, item, index) => { // 使用reduce,逐个检查是否重复,重复则push汝数组,其实这里可以找到重复即终止reduce。
if (temp === item) {
repeatArr.push(temp);
}
return item;
});
return repeatArr.length > 0 ? repeatArr[0] : -1;
};
alert(duplicateInArray(nums));
};