Skip to content

Commit 83fab38

Browse files
committedOct 18, 2017
add class Solution {
public: int singleNumber(vector<int>& nums) { int x = 0; for(int i=0;i<nums.size();i++){ x ^= nums[i]; } return x;
1 parent cc67bb5 commit 83fab38

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
 

‎leetcode/Single Number.md

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# Single Number
2+
Given an array of integers, every element appears twice except for one. Find that single one.
3+
## 解析
4+
* 首先是最简单的办法,就是挨个搜索每个元素是否出现了2次,这样的时间复杂度是O(n^2),代码就不写了。
5+
6+
* 可以先排序然后再搜索每个元素是否出现了两次。这样可以将时间复杂度降到O(nlogn)
7+
8+
```python
9+
class Solution:
10+
# @param A, a list of integer
11+
# @return an integer
12+
def singleNumber(self, A):
13+
A.sort()
14+
for i in range(1, len(A), 2):
15+
if A[i] != A[i-1]: # 与前一元素对比
16+
return A[i-1]
17+
return A[-1] # 要找的元素是最后一个元素
18+
```
19+
20+
* 超级炫酷的位运算方法。将所有元素异或起来,最后的结果就是我们要找的Single Number。因为a ^ a = 0, 0 ^ b = b
21+
22+
```c++
23+
class Solution {
24+
public:
25+
int singleNumber(vector<int>& nums) {
26+
int x = 0;
27+
for(int i=0;i<nums.size();i++){
28+
x ^= nums[i];
29+
}
30+
return x;
31+
}
32+
};
33+
```
34+
35+

0 commit comments

Comments
 (0)