auto commit
This commit is contained in:
35
notes/56. 数组中只出现一次的数字.md
Normal file
35
notes/56. 数组中只出现一次的数字.md
Normal file
@ -0,0 +1,35 @@
|
||||
# 56. 数组中只出现一次的数字
|
||||
|
||||
[NowCoder](https://www.nowcoder.com/practice/e02fdb54d7524710a7d664d082bb7811?tpId=13&tqId=11193&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
|
||||
|
||||
## 题目描述
|
||||
|
||||
一个整型数组里除了两个数字之外,其他的数字都出现了两次,找出这两个数。
|
||||
|
||||
## 解题思路
|
||||
|
||||
两个不相等的元素在位级表示上必定会有一位存在不同,将数组的所有元素异或得到的结果为不存在重复的两个元素异或的结果。
|
||||
|
||||
diff &= -diff 得到出 diff 最右侧不为 0 的位,也就是不存在重复的两个元素在位级表示上最右侧不同的那一位,利用这一位就可以将两个元素区分开来。
|
||||
|
||||
```java
|
||||
public void FindNumsAppearOnce(int[] nums, int num1[], int num2[]) {
|
||||
int diff = 0;
|
||||
for (int num : nums)
|
||||
diff ^= num;
|
||||
diff &= -diff;
|
||||
for (int num : nums) {
|
||||
if ((num & diff) == 0)
|
||||
num1[0] ^= num;
|
||||
else
|
||||
num2[0] ^= num;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<div align="center"><img width="320px" src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/githubio/公众号二维码-1.png"></img></div>
|
Reference in New Issue
Block a user