leetcode——Single Number III

题目一:

Given an array of integers, every element appears twice 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值