用python编写方法,找出1-n数组中没出现过的数
时间: 2024-05-06 09:20:28 浏览: 15
下面是一种使用Python语言的方法,可以找出1-n数组中没有出现过的数:
```python
def find_missing_numbers(n, arr):
"""
This function finds the missing numbers in an array of integers from 1 to n.
:param n: An integer representing the maximum value in the array.
:param arr: A list of integers representing the array.
:return: A list of integers representing the missing numbers.
"""
missing_numbers = []
# Create a set of all the numbers from 1 to n.
all_numbers = set(range(1, n+1))
# Create a set of the numbers in the array.
arr_set = set(arr)
# Iterate over the set of all numbers and check if they are in the array set.
# If not, add them to the missing numbers list.
for num in all_numbers:
if num not in arr_set:
missing_numbers.append(num)
return missing_numbers
```
使用示例:
```python
>>> arr = [1, 2, 4, 5, 7, 9]
>>> n = 10
>>> find_missing_numbers(n, arr)
[3, 6, 8, 10]
```
在这个例子中,数组中缺少的数字是3、6、8和10。
相关推荐
![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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![](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)