问题描述:
在一个班级中,每位同学都拿到了一张卡片,上面有一个整数。有趣的是,除了一个数字之外,所有的数字都恰好出现了两次。现在需要你帮助班长小C快速找到那个拿了独特数字卡片的同学手上的数字是什么。
要求:
设计一个算法,使其时间复杂度为 O(n),其中 n 是班级的人数。
尽量减少额外空间的使用,以体现你的算法优化能力。
测试样例:
样例1:
输入:cards = [1, 1, 2, 2, 3, 3, 4, 5, 5]
输出:4
解释:拿到数字 4 的同学是唯一一个没有配对的。
样例2:
输入:cards = [0, 1, 0, 1, 2]
输出:2
解释:数字 2 只出现一次,是独特的卡片。
样例3:
输入:cards = [7, 3, 3, 7, 10]
输出:10
解释:10 是班级中唯一一个不重复的数字卡片。
思路1
function solution(cards) {
if (!cards?.length) return null;
return cards.find(num => cards.filter(x => x === num).length === 1) || null;
}
function main() {
console.log(solution([1, 1, 2, 2, 3, 3, 4, 5, 5]) === 4);
console.log(solution([0, 1, 0, 1, 2]) === 2);
}
main();
思路2
function solution(cards) {
const countMap = new Map();
for (const num of cards) {
countMap.set(num, (countMap.get(num) || 0) + 1);
}
for (const [num, count] of countMap) {
if (count === 1) {
return num;
}
}
return null;
}
function main() {
console.log(solution([1, 1, 2, 2, 3, 3, 4, 5, 5]) === 4);
console.log(solution([0, 1, 0, 1, 2]) === 2);
}
main();