Skip to content

Commit d653195

Browse files
committed
只出现一次的数
1 parent f5a3eed commit d653195

File tree

4 files changed

+47
-0
lines changed

4 files changed

+47
-0
lines changed

LeetCode/Doc/出现一次的数.md

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# single-number(出现一次的数)
2+
3+
<center>知识点:复杂度</center>
4+
5+
6+
## 题目描述
7+
Given an array of integers, every element appears twice except for one. Find that single one.
8+
9+
Note:
10+
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
11+
12+
给定一个数组,除了某一个元素之外的其他元素都出现了两次,找出那个只出现了一次的数。
13+
14+
注意:你的算法应该在线性事件复杂度内完成,不应该使用额外空间。
15+
16+
17+
## 解题思路
18+
19+
使用异或操作,由于异或操作有"相同得0,不同得1"的特性,所以讲所有元素顺序异或完之后结果即为那个只出现了一次的数。
20+
21+
22+
## 代码
23+
24+
[这里](../src/fourteen/Solution.java)
Binary file not shown.
Binary file not shown.

LeetCode/src/fourteen/Solution.java

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package fourteen;
2+
3+
/**
4+
* @author dmrfcoder
5+
* @date 2019/4/10
6+
*/
7+
public class Solution {
8+
public int singleNumber(int[] A) {
9+
10+
11+
int res = A[0];
12+
for (int index = 1; index < A.length; index++) {
13+
res = res ^ A[index];
14+
}
15+
return res;
16+
}
17+
18+
public static void main(String[] args) {
19+
int[] A = {1, 2, 3, 2, 1};
20+
Solution solution = new Solution();
21+
System.out.println(solution.singleNumber(A));
22+
}
23+
}

0 commit comments

Comments
 (0)