Skip to content

Commit 0297b2a

Browse files
committed
feat: add python and java solutions to lcof problem
添加《剑指 Offer》题解:面试题56 - I. 数组中数字出现的次数
1 parent b665851 commit 0297b2a

File tree

3 files changed

+118
-0
lines changed

3 files changed

+118
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
# [面试题56 - I. 数组中数字出现的次数](https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof/)
2+
3+
## 题目描述
4+
一个整型数组 nums 里除两个数字之外,其他数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。
5+
6+
**示例 1:**
7+
8+
```
9+
输入:nums = [4,1,4,6]
10+
输出:[1,6] 或 [6,1]
11+
```
12+
13+
**示例 2:**
14+
15+
```
16+
输入:nums = [1,2,10,4,1,4,3,3]
17+
输出:[2,10] 或 [10,2]
18+
```
19+
20+
**限制:**
21+
22+
- `2 <= nums <= 10000`
23+
24+
## 解法
25+
### Python3
26+
```python
27+
class Solution:
28+
def singleNumbers(self, nums: List[int]) -> List[int]:
29+
xor_res = 0
30+
for num in nums:
31+
xor_res ^= num
32+
pos = 0
33+
while (xor_res & 1) == 0:
34+
pos += 1
35+
xor_res >>= 1
36+
37+
a = b = 0
38+
for num in nums:
39+
t = num >> pos
40+
if (t & 1) == 0:
41+
a ^= num
42+
else:
43+
b ^= num
44+
return [a, b]
45+
```
46+
47+
### Java
48+
```java
49+
class Solution {
50+
public int[] singleNumbers(int[] nums) {
51+
int xor = 0;
52+
for (int num : nums) {
53+
xor ^= num;
54+
}
55+
int pos = 0;
56+
while ((xor & 1) == 0) {
57+
++pos;
58+
xor >>= 1;
59+
}
60+
int a = 0, b = 0;
61+
for (int num : nums) {
62+
int t = num >> pos;
63+
if ((t & 1) == 0) {
64+
a ^= num;
65+
} else {
66+
b ^= num;
67+
}
68+
}
69+
return new int[] {a, b};
70+
}
71+
}
72+
```
73+
74+
### ...
75+
```
76+
77+
```
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution {
2+
public int[] singleNumbers(int[] nums) {
3+
int xor = 0;
4+
for (int num : nums) {
5+
xor ^= num;
6+
}
7+
int pos = 0;
8+
while ((xor & 1) == 0) {
9+
++pos;
10+
xor >>= 1;
11+
}
12+
int a = 0, b = 0;
13+
for (int num : nums) {
14+
int t = num >> pos;
15+
if ((t & 1) == 0) {
16+
a ^= num;
17+
} else {
18+
b ^= num;
19+
}
20+
}
21+
return new int[] { a, b };
22+
}
23+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution:
2+
def singleNumbers(self, nums: List[int]) -> List[int]:
3+
xor_res = 0
4+
for num in nums:
5+
xor_res ^= num
6+
pos = 0
7+
while (xor_res & 1) == 0:
8+
pos += 1
9+
xor_res >>= 1
10+
11+
a = b = 0
12+
for num in nums:
13+
t = num >> pos
14+
if (t & 1) == 0:
15+
a ^= num
16+
else:
17+
b ^= num
18+
return [a, b]

0 commit comments

Comments
 (0)