File tree 1 file changed +19
-1
lines changed
1 file changed +19
-1
lines changed Original file line number Diff line number Diff line change @@ -36,7 +36,7 @@ Your algorithm should have a linear runtime complexity. Could you implement it w
36
36
37
37
## 代码
38
38
39
- * 语言支持:JS,C++
39
+ * 语言支持:JS,C++,Python
40
40
41
41
JavaScrip Code:
42
42
``` js
@@ -109,6 +109,24 @@ public:
109
109
};
110
110
```
111
111
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
+
112
130
## 延伸
113
131
114
132
有一个 n 个元素的数组,除了两个数只出现一次外,其余元素都出现两次,让你找出这两个只出现一次的数分别是几,要求时间复杂度为 O(n) 且再开辟的内存空间固定(与 n 无关)。
You can’t perform that action at this time.
0 commit comments