File tree 3 files changed +38
-13
lines changed
solution/0100-0199/0136.Single Number
3 files changed +38
-13
lines changed Original file line number Diff line number Diff line change 26
26
## 解法
27
27
<!-- 这里可写通用的实现逻辑 -->
28
28
29
+ 异或运算求解。
30
+
31
+ 首先明确,两个相同的数异或之后的结果为 0。对该数组所有元素进行异或运算,结果就是那个只出现一次的数字。
29
32
30
33
<!-- tabs:start -->
31
34
32
35
### ** Python3**
33
36
<!-- 这里可写当前语言的特殊实现逻辑 -->
34
37
35
38
``` python
36
-
39
+ class Solution :
40
+ def singleNumber (self , nums : List[int ]) -> int :
41
+ res = 0
42
+ for num in nums:
43
+ res ^= num
44
+ return res
37
45
```
38
46
39
47
### ** Java**
40
48
<!-- 这里可写当前语言的特殊实现逻辑 -->
41
49
42
50
``` java
43
-
51
+ class Solution {
52
+ public int singleNumber (int [] nums ) {
53
+ int res = 0 ;
54
+ for (int num : nums) {
55
+ res ^ = num;
56
+ }
57
+ return res;
58
+ }
59
+ }
44
60
```
45
61
46
62
### ** ...**
Original file line number Diff line number Diff line change 52
52
### ** Python3**
53
53
54
54
``` python
55
-
55
+ class Solution :
56
+ def singleNumber (self , nums : List[int ]) -> int :
57
+ res = 0
58
+ for num in nums:
59
+ res ^= num
60
+ return res
56
61
```
57
62
58
63
### ** Java**
59
64
60
65
``` java
61
-
66
+ class Solution {
67
+ public int singleNumber (int [] nums ) {
68
+ int res = 0 ;
69
+ for (int num : nums) {
70
+ res ^ = num;
71
+ }
72
+ return res;
73
+ }
74
+ }
62
75
```
63
76
64
77
### ** ...**
Original file line number Diff line number Diff line change 1
1
class Solution :
2
- def singleNumber (self , nums ):
3
- """
4
- :type nums: List[int]
5
- :rtype: int
6
- """
7
- res = 0
8
- for i in nums :
9
- res = res ^ i
10
- return res
2
+ def singleNumber (self , nums : List [int ]) -> int :
3
+ res = 0
4
+ for num in nums :
5
+ res ^= num
6
+ return res
You can’t perform that action at this time.
0 commit comments