首页 > 其他 > 详细

只出现一次的数

时间:2016-09-17 14:58:01      阅读:169      评论:0      收藏:0      [点我收藏+]

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) {
    int x_xor_y = 0;
    for (int n: nums) {
        x_xor_y ^= n;
    }
    // 找到最后一位1 
    // 出现1表示,这一点处两个数的值不一样,一个为0一个为1,不然不可能异或出现1
    int mask = x_xor_y & ~(x_xor_y - 1);
    int x = 0;
    int y = 0;
    // x: XOR of a,a,b,b,x
    // y: XOR of c,c,y
    for (int n: nums) {
        if (n & mask) {
            x ^= n;
        } else {
            y ^= n;
        }
    }
    return vector<int> {x, y};
}
};

 

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

class Solution {
public:
    int singleNumber(int A[], int n) {
        int num = 0;
    for (size_t i = 0; i < n; ++i){
        num ^= A[i];
    }
    return num;
    }
};

 

Given an array of integers, every element appears three times except for one. Find that single one.

int singleNumber(vector<int> AA) {
    int ones = 0, twos = 0;
    //int size = sizeof(AA) / sizeof(int);
    for (int i = 0; i < AA.size(); i++){
        ones = (ones ^ AA[i]) & ~twos;
        twos = (twos ^ AA[i]) & ~ones;
    }
    return ones;
}

 

只出现一次的数

原文:http://www.cnblogs.com/ddddddwwwxx/p/5878743.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!