260. Single Number III(C++)

来源:互联网 发布:计算机二级vb题库2017 编辑:程序博客网 时间:2024/06/04 01:02

题目:

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?

class Solution {public:    vector<int> singleNumber(vector<int>& nums) {    }};

翻译:

给定一个数字nums的数组,其中恰好两个元素只出现一次,所有其他元素出现正好两次。 找到只出现一次的两个元素。

例如:

给定nums = [1,2,1,3,2,5],return [3,5]。

注意:
结果的顺序并不重要。 所以在上面的例子中,[5,3]也是正确的。
您的算法应以线性运行时复杂性运行。 你能实现它只使用恒定的空间复杂性?

思路:

首先比较好想到的还是排序,将这些数排序后相邻两个依次比较,一直比较到第二个没有相同数的值为止,就得到答案了。
当然,还发现这个题和以前做的:http://blog.csdn.net/zzlcsdn2017/article/details/59616340Single Number I(以后称I)有异曲同工之妙,这道题依然是需要用异或来求解:
如果还按I中方式,将所有数字都异或后得到的是其中单独的两个数的异或值,因为这两个数不同,异或后一定存在“1”,而其他值都相互异或为“0”了。那么就可以利用“1”(只用一个就够了,即使可能存在多个,就设定为从低位到高位的第一个“1”,假设为a位)将原来的数组分为两个,一个所有数字a位全是1,另一个是剩下的数字,相同的数字两两都分在了同一个组里,而不同的两个数字也被分开了,最后分别对这两个数组再一次全部异或,便分别得到我们想要的两个数字。

解答:

(94.69%)还是比较强的

class Solution {public:    vector<int> singleNumber(vector<int>& nums) {        int ax = 0;    int a = 0, b = 0;    for (int i = 0; i<nums.size(); i++)    {        ax ^= nums[i];    }    //for (int item : nums) {    //  ax ^= item;    //}    int lastb = (ax & (ax - 1)) ^ ax;    for (int item : nums) {        if (item & lastb) {            a ^= item;        }        else {            b ^= item;        }    }    /*for (int i = 0; i < nums.size();i++) {        if (nums[i] & lastb) {            a ^= nums[i];        }        else {            b ^= nums[i];        }    }*/    return vector<int>{a, b};    }};
  1. int lastb = (ax & (ax - 1)) ^ ax;//求二进制ax最小的1所在地。
  2. 第二个for循环直接合并步骤,用if省去了分组的事情,直接将
0 0
原创粉丝点击