-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSingleNumber3_NO260.java
57 lines (56 loc) · 1.51 KB
/
SingleNumber3_NO260.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public class SingleNumber3_NO260{
public int[] singleNumber(int[] nums)
{
HashMap<Integer,Integer> c = new HashMap<>();
for (int n:nums)
{
if (c.containsKey(n) == true )
c.remove(n);
else
c.put(n,null);
}
int i = 0;
int[] result = new int[2];
for (int k:c.keySet())
{
if (i < 2)
result[i++] = k;
else
break;
}
return result;
}
public int[] singleNumber2(int[] nums)
{
Arrays.sort(nums);
Stack<Integer> stack = new Stack<>();
int[] result = new int[2];
int rp = 0;
stack.push(nums[0]);
for (int i = 1;i<nums.length;++i) {
if (stack.empty() ||stack.peek()!= nums[i])
stack.push(nums[i]);
else
stack.pop();
}
while(stack.empty() == false){
result[rp++] = stack.pop();
}
return result;
}
public int[] singleNumber3(int[] nums)
{
int diff = 0;
int[] result = new int[2];
for (int n:nums)
{
diff ^= nums;//两个不同的数异或后的结果,一定至少有一位为1。把这一位挑出来用来区分这两个数。
}
diff &= -diff; //一个数的补码一定有一位与原码同为1,通过这样的方法找出上述的这一位。
for (int n:nums)
{
result[!(nums & diff)]^=nums;
}
return result;
}
}