Skip to content

Commit 8e2cb85

Browse files
ybian19azl397985856
authored andcommitted
feat: 136.single-number add Python3 implementation (azl397985856#91)
* feat: 136.single-number add Python3 implementation * update
1 parent f74475c commit 8e2cb85

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

problems/136.single-number.md

+19-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ Your algorithm should have a linear runtime complexity. Could you implement it w
3636

3737
## 代码
3838

39-
* 语言支持:JS,C++
39+
* 语言支持:JS,C++,Python
4040

4141
JavaScrip Code:
4242
```js
@@ -109,6 +109,24 @@ public:
109109
};
110110
```
111111
112+
Python Code:
113+
114+
```python
115+
class Solution:
116+
def singleNumber(self, nums: List[int]) -> int:
117+
single_number = 0
118+
for num in nums:
119+
single_number ^= num
120+
return single_number
121+
122+
# 另一种思路:集合是无序不重复的元素集
123+
# 利用这一特性将列表转化成不包含重复元素的集合
124+
# 分别对集合和列表进行求和,集合元素之和 x2 减去列表元素之和即为只出现了一次的元素
125+
class Solution:
126+
def singleNumber(self, nums: List[int]) -> int:
127+
return 2 * sum(set(nums)) - sum(nums)
128+
```
129+
112130
## 延伸
113131

114132
有一个 n 个元素的数组,除了两个数只出现一次外,其余元素都出现两次,让你找出这两个只出现一次的数分别是几,要求时间复杂度为 O(n) 且再开辟的内存空间固定(与 n 无关)。

0 commit comments

Comments
 (0)