Skip to content

Commit aab3b27

Browse files
authored
【268. 丢失的数字】【 python3】
【268. 丢失的数字】【 python3】
2 parents ea2301d + ab8b9e2 commit aab3b27

File tree

1 file changed

+31
-3
lines changed

1 file changed

+31
-3
lines changed

高频面试系列/消失的元素.md

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -132,9 +132,39 @@ public int missingNumber(int[] nums) {
132132
<p align='center'>
133133
<img src="../pictures/qrcode.jpg" width=200 >
134134
</p>
135-
136135
======其他语言代码======
137136

137+
### python
138+
139+
```python
140+
def missingNumber(self, nums: List[int]) -> int:
141+
#思路1,位运算
142+
res = len(nums)
143+
for i,num in enumerate(nums):
144+
res ^= i^num
145+
return res
146+
```
147+
148+
```python
149+
def missingNumber(self, nums: List[int]) -> int:
150+
#思路2,求和
151+
n = len(nums)
152+
return n*(n+1)//2-sum(nums)
153+
```
154+
155+
```python
156+
def missingNumber(self, nums: List[int]) -> int:
157+
#思路3,防止整形溢出的优化
158+
res = len(nums)
159+
for i,num in enumerate(nums):
160+
res+=i-num
161+
return res
162+
```
163+
164+
事实上,在python3中不存在整数溢出的问题(只要内存放得下),思路3的优化提升并不大,不过看上去有内味了哈...
165+
166+
### c++
167+
138168
[happy-yuxuan](https://github.com/happy-yuxuan) 提供 三种方法的 C++ 代码:
139169

140170
```c++
@@ -177,5 +207,3 @@ int missingNumber(vector<int>& nums) {
177207
return res;
178208
}
179209
```
180-
181-

0 commit comments

Comments
 (0)