题目
同样是 codewar 的一道题
Given an array of integers, find the one that appears an odd number of times. There will always be only one integer that appears an odd number of times.
提供一个整形数组,找到一个出现了奇数次的数字并返回。只需要返回一个就行。
|
|
实例:
[7] should return 7, because it occurs 1 time (which is odd).
[0] should return 0, because it occurs 1 time (which is odd).
[1,1,2] should return 2, because it occurs 1 time (which is odd).
[0,1,0,1,0] should return 0, because it occurs 3 times (which is odd).
[1,2,2,3,3,3,4,3,3,3,2,2,1] should return 4, because it appears 1 time (which is odd).
题解
题目内容很简单,只需要一个个遍历元素同时数出该元素一共有几个,当这个元素遍历完计数是奇数个就退出循环返回元素。
需要两个 for
循环,因为题目给的是 vector
所以可以用迭代器(iterator)来循环。
两层嵌套循环就可以解决了,代码如下
|
|
他人解法
我所写的只用到了迭代器,而 C++ 还有非常多好用的内置函数可以更好的解决问题。
count()
使用 <algorithm>
库内的 count()
对元素进行计数可以将内循环省掉,提j高代码的阅读性。
|
|
count()
的用法为:
|
|
unordered_map<>
使用 unordered_map
数据类型可以将每一个元素出现的次数整合在一起。
|
|