# LeetCode笔记：260. Single Number III

381人阅读 评论(0)

## 问题：

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;
}
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：520166次
• 积分：8861
• 等级：
• 排名：第2130名
• 原创：250篇
• 转载：9篇
• 译文：132篇
• 评论：89条
关于博主
博客专栏
 Motion Design for iOS 文章：46篇 阅读：72761
 LeetCode笔记 文章：143篇 阅读：92729
 拾遗iOS之海 文章：109篇 阅读：224556
 iOS Human Interface Guidelines 文章：84篇 阅读：93045
阅读排行
评论排行
最新评论