CS-Notes/notes/56. 数组中只出现一次的数字.md
2019-11-02 12:07:41 +08:00

36 lines
1.2 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 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>