前言
在一个班级中,每位同学都拿到了一张卡片,上面有一个整数。有趣的是,除了一个数字之外,所有的数字都恰好出现了两次。现在需要你帮助班长小C快速找到那个拿了独特数字卡片的同学手上的数字是什么。
要求:
- 设计一个算法,使其时间复杂度为 O(n),其中 n 是班级的人数。
- 尽量减少额外空间的使用,以体现你的算法优化能力。
实现
Python版
def solution(cards):
# Edit your code here
d = {}
for c in cards:
if c in d :
d[c] += d[c]+1
else:
d[c] = 1
for key in d.keys():
if d[key] == 1:
return key
return 0
if __name__ == "__main__":
# Add your test cases here
print(solution([1, 1, 2, 2, 3, 3, 4, 5, 5]) == 4)
print(solution([0, 1, 0, 1, 2]) == 2)
js版本
function solution(cards) {
// Edit your code here
let match = new Map()
cards.forEach(el => {
if (match.has(el)) {
let node = match.get(el)
match.set(el, node + 1)
} else {
match.set(el, 1)
}
});
for(let [key,value] of Array.from(match.entries())){
if (value == 1) {
return key
}
}
return 0;
}
function main() {
// Add your test cases here
console.log(solution([1, 1, 2, 2, 3, 3, 4, 5, 5]) === 4);
console.log(solution([0, 1, 0, 1, 2]) === 2);
}
main();