题目链接:http://oj.leetcode.com/problems/single-number-ii/
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?
解法:由于数组中所有元素都是整型,整型长度为32位,可以用一个数组count[32]记录所有元素按位出现1的总数,然后count[i]=count[i]%3,这样做可以将出现三次元素的每位
置为0,最后数组count[32]为出现一次元素的每位.
1 class Solution { 2 public: 3 int singleNumber(int A[], int n) { 4 // IMPORTANT: Please reset any member data you declared, as 5 // the same Solution instance will be reused for each test case. 6 7 const int L = sizeof(int) * 8; 8 int count[L], i, j, result = 0; 9 fill_n(&count[0], L, 0); 10 for (i = 0; i < L; i++) 11 { 12 for (j = 0; j < n; j++) 13 { 14 count[i] += ((A[j] >> i) & 1); 15 count[i] %= 3; 16 } 17 } 18 19 20 for (i = 0; i < L; i++) 21 { 22 result += (count[i] << i); 23 } 24 return result; 25 } 26 };