数组中只出现一次的数字
题目描述解法一解法二
题目描述
一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
解法一
时间复杂度O(n),空间O(n)
使用一个Map来存储每个数值以及其对应的计数,最后遍历输出这个计数为1的两个值
import java
.util
.Map
;
import java
.util
.HashMap
;
public class Solution {
public void FindNumsAppearOnce(int [] array
,int num1
[] , int num2
[]) {
Map
<Integer, Integer> map
= new HashMap<>();
for(int n
: array
){
if(map
.containsKey(n
)){
map
.put(n
, 2);
}else{
map
.put(n
, 1);
}
}
int i
= 0;
for(Integer key
: map
.keySet()){
if(map
.get(key
) == 1){
if(i
== 0){
num1
[0] = key
;
i
++;
} else{
num2
[0] = key
;
break;
}
}
}
}
}
解法二
时间O(n),空间O(1)
public class Solution {
public void FindNumsAppearOnce(int [] array
,int num1
[] , int num2
[]) {
int res
= 0;
for(int num
: array
){
res
^= num
;
}
num1
[0] = 0;
num2
[0] = 0;
res
= res
& (-res
);
for(int num
: array
){
if((res
& num
) >= 1){
num1
[0] ^= num
;
} else{
num2
[0] ^= num
;
}
}
}
}