[leetcode]Single Number II

来源:互联网 发布:three.js 球体 编辑:程序博客网 时间:2024/06/05 15:38

Single Number II

 My Submissions

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?

Have you been asked this question in an interview? 

题目:除了一个元素以外其它元素出现3次,而只有一个元素出现一次

思路:将每个元素转化成二进制并将其对应的bit位置1,所以出过三次的元素对应的位应该是3的倍数,而最后只会剩下那只出现一次元素所对应的二进制位。

    int singleNumber(int a[], int n) {        int bitCount[32] = {0};                for(int i = 0; i < n; i++){            int bit = 1;            for(int j = 0; j < 32; j++){                if(bit & a[i]){                    bitCount[j] = (bitCount[j] + 1) % 3;                }                bit <<= 1;            }        }                int retNum = 0;                for(int i = 0; i < 32; i++){                        retNum = retNum * 2 + bitCount[31 - i];        }                return retNum;    }

如果对其进一步可作扩展,除一个元素出现2次其它都出现3次,也可以用此方法。
如一个元素出现两次,一个出现1次,其它出现4次。也可以



0 0
原创粉丝点击