leetcode——Single Number III

来源:互联网 发布:农村淘宝服务站怎么绑 编辑:程序博客网 时间:2024/04/29 13:55

题目一:

Given an array of integers, every element appearstwice except for one. Find that single one.

class Solution {public:    int singleNumber(vector<int>& nums) {        int res = 0;        for (auto n : nums)         {            res ^= n;        }                return res;    }};
题目二
Given an array of integers, every element appears three times except for one. Find that single one. 

class Solution {public:    int singleNumber(vector<int>& nums) {        int one = 0, two = 0, three = 0;        for (auto n : nums)         {            two |= one & n; //出现次数>=2的位            one ^= n; //出现次数为奇数的位            three = one & two;//出现三次的位            one &= ~three;//奇数不是3那就是1            two &= ~three;//>=2不是3那就是2        }                return one;    }};
题目三

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].

class Solution {public:    vector<int> singleNumber(vector<int>& nums) {        //假设那两个不同的数为a,b        //所有数异或得到a^b        int a_b = 0;        for (auto n : nums)         {            a_b ^= n;        }                //由于a!=b,所以a^b中肯定有一位是1,找出来,并按照该位分类异或,得到a,b        int mask = 0x1;        int nBits = sizeof(int) * 8;        while (!(a_b & mask))        {            mask = mask << 1;        }                int a = 0, b = 0;        for (auto n : nums)         {            if (n & mask)             {                a ^= n;            }            else             {                b ^= n;            }        }                vector<int> res(2);        res[0] = a;        res[1] = b;        return res;    }};


0 0
原创粉丝点击