Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ae176cc

Browse files
🐱(offer): 面试题56 - I. 数组中数字出现的次数
1 parent 8053cf4 commit ae176cc

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

‎docs/offer/README.md‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -450,6 +450,37 @@ class Solution:
450450
return cur
451451
```
452452

453+
## 面试题56 - I. 数组中数字出现的次数
454+
455+
[原题链接](https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof/)
456+
457+
### 思路:异或
458+
459+
1. 求出所有数异或的结果
460+
2. 结果中为 1 的位表示两个数不同数字的位
461+
3. 根据这个为 1 的位置把 `nums` 分成两组分别异或就可以得出结果
462+
463+
```python
464+
class Solution:
465+
def singleNumbers(self, nums: List[int]) -> List[int]:
466+
ret = 0
467+
for n in nums:
468+
ret ^= n
469+
# 找出从右到左第一个为 1 的数
470+
index = 0
471+
while ret & 1 == 0:
472+
# 右移 1 位
473+
ret >>= 1
474+
index += 1
475+
a, b = 0, 0
476+
for n in nums:
477+
if (n >> index) & 1 == 0:
478+
a ^= n
479+
else:
480+
b ^= n
481+
return [a, b]
482+
```
483+
453484
## 面试题57 - II. 和为s的连续正数序列
454485

455486
[原题链接](https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /