您的位置:首页 > 其它

LeetCode 260 Single Number III(数组中只出现一次的数字3)

2016-02-18 15:06 555 查看

原文

[code]给定一个数字数组nums,其中有两个元素只出现一次,而其他所有元素均出现两次。

找出这两个只出现一次的元素。

例如:

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

备注:
1, 返回结果的顺序不重要。所以在上例中,返回[3, 5]也是正确的。
2, 你的算法应该运行在线性时间复杂度。你可以只用常量空间复杂度来实现它吗?


原文

[code]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?


分析

本题我曾在《剑指Offer》中见过,记得要用位运算,自己实现了一遍,不过再看了看书上的,并没有书上的规范,所以最后贴了书上的代码……

其实有这么一个性质:

任何数字异或其自身都等于零。

可能有读者不了解什么是异或,那么就来插播一下:

异或,英文为exclusiveOR,或缩写成xor,异或是一个被用于逻辑运算的数学符号。其数学符号是“⊕”,计算机符号是“xor”。

a⊕b=(¬a∧b)∨(a∧¬b)

true ⊕ false -> true

false ⊕ true -> true

true ⊕ true -> false

false ⊕ false -> false

也就是说两个值相同则异或结果为假,两个值不同则异或为真。所以任何数字异或其自身都等于零,因为两个值相同。

好了,切入正题。就以题目中给出的数组为例吧:

[code][1, 2, 1, 3, 2, 5, 6, 5, 4, 6]

分别换算成二进制如下:
0001、0010、0001、0011、0010
0101、0110、0101、0100、0110

对所有数组进行异或运算得出的结果是:0111

于是进行分组如下:
A组: 0001(1)、0010(2)、0001(1)、0011(3)、0010(2)
B组: 0101(5)、0110(6)、0101(6)、0100(4)、0110(5)

对A组进行再次异或运算的结果是:0011(3)

对B组进行再次异或运算的结果是:0100(4)


判断该数字的二进制第n位是否是1的函数:

[code]bool IsBit1(int num, unsigned int index) {
    num = num >> index;
    return (num & 1);
}`


找出该数字二进制中第一个1的函数:

[code]unsigned int FindFirstBigIs1(int num) {
    int indexBit = 0;
    while (((num & 1) == 0) && (indexBit < 8 * sizeof(int))) {
        num = num >> 1;
        ++indexBit;
    }
    return indexBit;
}


根据LeetCode的函数模板修改了一点:

[code]vector<int> singleNumber(vector<int>& nums) {
    vector<int> singleV;
    if (nums.size() <= 0) return singleV;

    int resultExclusiveOR = 0;
    for (int i = 0; i < nums.size(); ++i)
        resultExclusiveOR ^= nums[i];

    unsigned int indexOf1 = FindFirstBigIs1(resultExclusiveOR);

    int singleNum1 =0, singleNum2 = 0;
    for (int j = 0; j < nums.size(); ++j) {
        if (IsBit1(nums[j], indexOf1))
            singleNum1 ^= nums[j];
        else
            singleNum2 ^= nums[j];    
    }

    singleV.push_back(singleNum1);
    singleV.push_back(singleNum2);
    return singleV;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: