[LeetCode OJ]Single number II

来源:互联网 发布:耐思尼克域名注册平台 编辑:程序博客网 时间:2024/05/24 07:30
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?


两次的时候可以异或(XOR),三次怎么搞,完全不会做= =

还是二进制,网上搜的,看了几个解释感觉也不是特别懂,不过推算了一趟循环发现还真是那么回事。。。


class Solution {public:    int singleNumber(int A[], int n) {        int one = 0;        int two = 0;        int three = 0;        for(int i = 0; i < n; i++) {            three = two & A[i]; //已经出现两次并且再次出现              two = two | one & A[i]; //曾经出现两次的或者曾经出现一次但是再次出现的              one = one | A[i]; //出现一次的                            two = two & ~three; //当某一位出现三次后,我们就从出现两次中消除该位              one = one & ~three; //当某一位出现三次后,我们就从出现一次中消除该位        }        return one;    }};



0 0
原创粉丝点击