只出现一次的数字的封装
时间: 2023-12-03 13:42:47 浏览: 36
以下是一个只出现一次的数字的封装的示例:
```
class SingleNumberFinder:
def __init__(self, nums):
self.nums = nums
def find_single_number(self):
"""
Return the only number that appears only once in the array.
"""
num_count = {}
for num in self.nums:
if num in num_count:
num_count[num] += 1
else:
num_count[num] = 1
for num, count in num_count.items():
if count == 1:
return num
return None
```
使用示例:
```
arr = [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6]
finder = SingleNumberFinder(arr)
print(finder.find_single_number()) # Output: 7
```
在这个示例中,`SingleNumberFinder` 类接受一个包含数字的 `nums` 数组。 `find_single_number` 方法在数组中查找唯一出现一次的数字,并返回该数字。