Skip to content

Commit 1f25642

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

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed

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

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# single-number-ii(出现一次的数2)
2+
3+
<center>知识点:复杂度</center>
4+
5+
6+
## 题目描述
7+
Given an array of integers, every element appears three times except for one. Find that single one.
8+
Note:
9+
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
10+
11+
给定一个数组,除了某一个元素之外的其他元素都出现了三次,找出那个只出现了一次的数。
12+
13+
注意:你的算法应该在线性事件复杂度内完成,不应该使用额外空间。
14+
15+
## 解题思路
16+
17+
这道题是对single-number的升级,首先回想一下single-number是如何解的,它是用异或运算异或了所有数组中的值最后返回结果,其本质是使用异或计算出所有数中对应bit位只出现了一次的数,如果某一个位有两个数都出现过(两个数一样的情况下),那么那个位就位0,如果某一位只出现过一次,那么那一位就为1。按照这个思路,我们这里只要找出所有数中bit位只出现过1次的就可以,出现过三次的、两次的,都应该是0,那么我们使用三个变量:a ,b,c。
18+
19+
a记录bit位出现过1次1的数值,b记录bit位出现过2次1的数值,c记录bit位出现过3次的位(c=b&a),然后将c中bit值为1的清空为0的就可以了。
20+
21+
22+
23+
24+
## 代码
25+
26+
[这里](../src/fifteen/Solution.java)

LeetCode/src/fifteen/Solution.java

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package fifteen;
2+
3+
/**
4+
* @author dmrfcoder
5+
* @date 2019/4/10
6+
*/
7+
public class Solution {
8+
public int singleNumber(int[] A) {
9+
10+
int a = 0;//只出现过1次的位
11+
int b = 0;//出现过2次的位
12+
int c;//出现过三次的位
13+
for (int index = 0; index < A.length; index++) {
14+
b = b | (a & A[index]);//之前的b或上现在的出现了2次的位
15+
a = a ^ A[index];//只出现过1次的位
16+
c = a & b;
17+
a = a & (~c);//抹去出现了3次的bits,~c将原来是1的都变为0,这样那些为与完之后结果一定是0,原来为0的变为1,这样与的结果由a决定
18+
b = b & (~c);
19+
20+
}
21+
return a;
22+
}
23+
24+
}

README.md

+4
Original file line numberDiff line numberDiff line change
@@ -155,4 +155,8 @@
155155
- [word-break(单词切分)](./LeetCode/Doc/单词切分.md)
156156
- [word-break-ii(单词切分2)](./LeetCode/Doc/单词切分2.md)
157157
- [copy-list-with-random-pointer(拷贝具有随机指针的链表)](./LeetCode/Doc/拷贝具有随机指针的链表.md)
158+
- [single-number(出现一次的数)](./LeetCode/Doc/出现一次的数.md)
159+
- [**single-number-ii(出现一次的数2)**](./LeetCode/Doc/出现一次的数2.md)
160+
161+
158162

0 commit comments

Comments
 (0)