码迷,mamicode.com
首页 > 其他好文 > 详细

只出现一次的数

时间:2016-09-17 15:01:06      阅读:149      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!