JavaScript 查找数组中出现一次的元素,其他元素都出现两次的程序
给定一个由n个元素组成的整数数组,其中每个元素都出现两次,除了一个元素。任务是在JavaScript中找到只在输入数组中出现一次的元素。
示例:
Input : arr = [ 5, 9, 2, 7, 4, 6, 1, 5, 1, 4, 6, 3, 7, 8, 2, 9 ]
Output : 3
Explanation: The input array consists of 17 elements
where all elements except 3 appears twice i.e.
(1, 2, 4, 5, 6, 7, 8, 9) are repeating twice. Hence
the answer will be 3.
Input : arr = [ 4, 7, 1, 4, 1 ]
Output : 7
在数组中找到只出现一次的元素的方法,其中其他元素都出现两次:
- 使用数组的filter()和indexOf()方法
- 使用带有XOR运算符的数组forEach()循环
使用数组filter()和indexOf()方法找到数组中只出现一次的元素的JavaScript程序
解决问题的第一种方法是使用数组的 filter() 方法。它将返回一个新的数组uniqueArr。现在,在输入数组上执行filter()方法,并检查当前元素在数组中的索引是否等于数组中元素的最后一个索引。因为如果它们相等,那么该元素是唯一的。打印uniqueArr数组的第一个元素。
示例: 此示例实现了使用数组filter()和indexOf()方法获取元素。
JavaScript
const arr = [
5, 9, 2, 7, 4, 6, 8, 1, 5,
1, 4, 6, 3, 7, 8, 2, 9
];
const uniqueArr = arr.filter((num) => {
return arr.indexOf(num) === arr.lastIndexOf(num);
});
console.log(uniqueArr);
输出
[ 3 ]
使用forEach()循环和XOR运算符在数组中找到只出现一次的元素的JavaScript程序
解决这个问题的另一种方法是使用XOR运算符(^)。
- 将ans初始化为0。
- 现在在数组中应用forEach循环,并对每个元素执行其与ans的XOR操作并返回ans。
- 由于XOR是可交换和可结合的,它将取消数组中的任何重复项,只有唯一的元素将包含在ans中。
- 打印ans。
例子: 此示例使用Array filter和XOR运算符来获取所需结果
Javascript
const arr = [
5, 9, 2, 7, 4, 6, 8, 1, 5,
1, 4, 6, 3, 7, 8, 2, 9
];
let ans = 0;
arr.forEach((num) => {
ans ^= num;
});
console.log(ans);
输出
3