从给定列表中找出只出现一次的数,如:给出[1,2,2,3,1,4,3],返回4。 【样例输入】 1 2 2 3 1 4 3 【样例输出】 4
时间: 2024-05-01 16:19:52 浏览: 25
可以使用哈希表来解决这个问题,遍历列表,将每个数字作为键,出现次数作为值存储在哈希表中。然后再次遍历列表,找到只出现一次的数字即可。
以下是 Python 代码实现:
```python
def find_unique(nums):
count = {}
for num in nums:
count[num] = count.get(num, 0) + 1
for num in nums:
if count[num] == 1:
return num
return None
```
其中,`count` 是一个字典,用于记录每个数字出现的次数。第一个循环遍历列表,将每个数字出现的次数存储在字典 `count` 中。第二个循环遍历列表,找到只出现一次的数字并返回。如果没有找到,则返回 `None`。
使用样例:
```python
nums = [1, 2, 2, 3, 1, 4, 3]
print(find_unique(nums)) # 输出 4
```
相关问题
从给定列表中找出只出现一次的数,如:给出[1,2,2,3,1,4,3],返回4 的python代码
好的,以下是一种实现方式:
```python
def find_single_number(nums):
"""
在给定列表中找出只出现一次的数
:param nums: 给定列表
:return: 只出现一次的数
"""
# 使用字典来记录每个数出现的次数
count_dict = {}
for num in nums:
count_dict[num] = count_dict.get(num, 0) + 1
# 遍历字典,找出只出现一次的数
for num, count in count_dict.items():
if count == 1:
return num
# 如果没有找到只出现一次的数,则返回 None
return None
```
使用示例:
```python
nums = [1, 2, 2, 3, 1, 4, 3]
result = find_single_number(nums)
print(result) # 输出 4
```
希望能帮到您!
从给定列表中找出只出现一次的数,如:给出[1,2,2,3,1,4,3],返回4,用python写
可以使用Python中的字典来记录每个数字出现的次数,然后再遍历字典找出只出现一次的数字。代码如下:
```python
def find_unique_num(nums):
num_counts = {}
for num in nums:
if num in num_counts:
num_counts[num] += 1
else:
num_counts[num] = 1
for num, count in num_counts.items():
if count == 1:
return num
return None # 如果没有只出现一次的数字,返回None
nums = [1, 2, 2, 3, 1, 4, 3]
print(find_unique_num(nums)) # 输出 4
```
首先创建一个空字典`num_counts`,然后遍历`nums`中的每个数字,如果该数字已经在字典中,则将其对应的值加1,否则将该数字加入字典并将其对应的值设为1。接着再次遍历字典,找出只出现一次的数字并返回。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)