LeetCode Single Number II

来源:互联网 发布:python内置函数 编辑:程序博客网 时间:2024/06/05 05:52

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

题意:有一个数组,只有一个数出现一次,其他的都出现三次,找出一次的数

思路:首先我们想到是每次把每一位二进制上1的个数都mod3,然后就能找出一个的了,但是这样空间太大了,所以我们想能记录每一次出现三次的时候就清0,那么我们需要先记录1次的,然后记录2次的,这样就能求出三次的了,最后再更新出现1次和2次的(也就是清0出现三次的位置),最后one代表的就是出现1次的了,

class Solution {  public:      int singleNumber(int A[], int n) {          int one = 0, two = 0, three = 0;        for (int i = 0; i < n; i++) {            two |= A[i] & one;            one = A[i] ^ one;            three = ~(one & two);            one &= three;            two &= three;        }        return one;    }};  



0 0