Single Number II

来源:互联网 发布:快手特效软件大全 编辑:程序博客网 时间:2024/05/05 00:39
-----QUESTION-----

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

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

-----SOLUTION-----


class Solution {public:    int singleNumber(int A[], int n) {        int once = 0;          int twice = 0;            for (int i = 0; i < n; i++) {              twice |= once & A[i]; //the num appeared 2 times              once ^= A[i];  //the num appeared 1 times            int not_three = ~(once & twice);  //the num appeared 3 times            once = not_three & once;  //remove num appeared 3 times from once            twice = not_three & twice;  //remove num appeared 3 times from twice        }          return once;      }};

0 0
原创粉丝点击