【268. 丢失的数字】【 python3】

【268. 丢失的数字】【 python3】
This commit is contained in:
BruceCat 2021-03-20 16:13:02 +08:00 committed by GitHub
commit aab3b27977
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 31 additions and 3 deletions

View File

@ -132,9 +132,39 @@ public int missingNumber(int[] nums) {
<p align='center'>
<img src="../pictures/qrcode.jpg" width=200 >
</p>
======其他语言代码======
### python
```python
def missingNumber(self, nums: List[int]) -> int:
#思路1,位运算
res = len(nums)
for i,num in enumerate(nums):
res ^= i^num
return res
```
```python
def missingNumber(self, nums: List[int]) -> int:
#思路2,求和
n = len(nums)
return n*(n+1)//2-sum(nums)
```
```python
def missingNumber(self, nums: List[int]) -> int:
#思路3,防止整形溢出的优化
res = len(nums)
for i,num in enumerate(nums):
res+=i-num
return res
```
事实上在python3中不存在整数溢出的问题只要内存放得下思路3的优化提升并不大不过看上去有内味了哈...
### c++
[happy-yuxuan](https://github.com/happy-yuxuan) 提供 三种方法的 C++ 代码:
```c++
@ -177,5 +207,3 @@ int missingNumber(vector<int>& nums) {
return res;
}
```