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?

解析:

其实这题好像把异或升级成三目运算,也就是说异或三个数,这三个数对应位都相同为0,都不同为1

可以用一个数组存储每位出现的个数,最后%3,余下的位组成的数字就是single num

 1 class Solution {
 2 public:
 3     int singleNumber(vector<int>& nums) {
 4         int n = sizeof(int) * 8;
 5         int count[n] = {0};
 6         vector<int>::size_type i = 0;
 7         for(i;i < nums.size();i++)
 8             for(int j = 0; j < n;j++)
 9                 count[j] += ( nums[i] >> j ) & 1;
10         for(int j = 0; j < n;j++)
11             count[j] %= 3;
12 
13         int result = 0;
14         for(int j = 0; j < n;j++)
15             result +=( count[j] << j );
16         return result;
17     }
18 };
原文地址:https://www.cnblogs.com/raichen/p/4958783.html