# LeetCode笔记：260. Single Number III

## 问题：

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

Note:
1. The order of the result is not important. So in the above example, [5, 3] is also correct.
2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

## 大意：

1. 结果的顺序不重要，所以上面的例子中 [5, 3] 也是对的。
2. 你的算法应该为线性的时间复杂度。你能不能只用恒定的空间复杂度？

## 代码（Java）：

public class Solution {
public int[] singleNumber(int[] nums) {
Arrays.sort(nums);

int[] result = new int[2];
int index = 0;

int i = 0;
for (; i < nums.length-1; i++) {
if (nums[i] != nums[i+1]) {
result[index] = nums[i];
index ++;
}
else i++;
}
if (i < nums.length) result[index] = nums[i];

return result;
}
}

## 他山之石：

public class Solution {
public int[] singleNumber(int[] nums) {
// Pass 1 :
// Get the XOR of the two numbers we need to find
int diff = 0;
for (int num : nums) {
diff ^= num;
}
// Get its last set bit
diff &= -diff;

// Pass 2 :
int[] rets = {0, 0}; // this array stores the two numbers we will return
for (int num : nums)
{
if ((num & diff) == 0) // the bit is not set
{
rets[0] ^= num;
}
else // the bit is set
{
rets[1] ^= num;
}
}
return rets;
}
}

#### [leetcode] 260.Single Number III

2015-08-17 17:42:59

#### [LeetCode 260] Single Number III

2015-09-13 04:22:02

#### LeetCode 260 Single Number III（只出现一次的数字 III）（*）

2016-02-18 15:06:24

#### LeetCode（260） Single Number III

2015-12-02 14:41:41

#### 260. Single Number III [medium] (Python)

2016-07-30 10:58:25

#### LeetCode Single Number III 异或＋补码

2015-11-15 22:23:51

#### 数组中出现一次的两个数 leetcode Single Number III

2015-09-09 11:28:38

#### 136. Single Number [medium] (Python)

2016-07-29 14:30:31

#### LeetCode OJ 之 Single Number III （唯一的数字-三）

2015-08-19 15:05:29

#### leetcode 260. Single Number III

2016-05-24 16:23:38