問題描述:
在一個班級中,每位同學都拿到了一張卡片,上面有一個整數(shù)。有趣的是,除了一個數(shù)字之外,所有的數(shù)字都恰好出現(xiàn)了兩次?,F(xiàn)在需要你幫助班長小C快速找到那個拿了獨特數(shù)字卡片的同學手上的數(shù)字是什么。
要求:
設(shè)計一個算法,使其時間復(fù)雜度為 O(n),其中 n 是班級的人數(shù)。
盡量減少額外空間的使用,以體現(xiàn)你的算法優(yōu)化能力。
測試樣例:
樣例1:
輸入:cards = [1, 1, 2, 2, 3, 3, 4, 5, 5]
輸出:4
解釋:拿到數(shù)字 4 的同學是唯一一個沒有配對的。
樣例2:
輸入:cards = [0, 1, 0, 1, 2]
輸出:2
解釋:數(shù)字 2 只出現(xiàn)一次,是獨特的卡片。
樣例3:
輸入:cards = [7, 3, 3, 7, 10]
輸出:10
解釋:10 是班級中唯一一個不重復(fù)的數(shù)字卡片。
思路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();