25 : Single Number III

来源:互联网 发布:图像语义分割算法论文 编辑:程序博客网 时间:2024/06/12 00:15

题目: 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:
The order of the result is not important. So in the above example, [5, 3] is also correct.
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

解析:如果我们能够把两个只出现一次且不同的数分到两个不同的小组中,然后再在这两个小组中分别调用Single number的解法就可以得到答案;分到两个不同的小组的方法如下:

1: 将数组中所有元素都做 “异或” 运算,最终的结果就等价于这两个不同的且分别只出现一次的元素做 “异或” 运算,由于这两个元素是不同的,因此 “异或” 后一定有一位(bit)为 1(对应的就是这两个不同的元素中,一个元素在此位上为1,另外一个元素在此位上为0);
2:假设上述 “异或” 运算后的值为 a, a &= -a 的结果表示的是仅仅保留 a 的 最右端 为 1 的位,其它位则全为0;

3:然后挨个地与数组中所有元素 “相与”,与数组中两个出现仅一次的元素 “相与” 后的结果分别是 1 和 0, 则我们就可以根据这个 0 和 1 的运算结果把这两个出现仅一次的元素分在两个不同的小组中,然后分别将这两个小组的元素”异或”,则就可以得到结果。

解题代码如下:

//解决的问题是 Single Number III//时间复杂度为 O(n),空间复杂度为 O(1)class Solution {public:        int singleNumber(vector<int>& nums) {                int tmp = 0;                for (auto val : nums)                        tmp ^= val;                tmp &= -tmp;                vector<int> result(2, 0);                for (auto val : nums)                        if (tmp & val) result[0] ^= val;                        else result[1] ^= val;                return result;        }};
0 0
原创粉丝点击