标签:
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?
分析:找出数组里面的仅出现一次的数字(其余全部出现三次)。
可以将所有数字的二进制码都按位进行数字相加,得到每个位上1和0出现的次数,然后在每个位上对3取余。
例如: 1 1 1 1 0 0 0 1
0 1 0 1 0 1 0 1
1 0 1 0 1 1 0 1
按位相加:2 2 2 2 1 2 0 3
取余: 2 2 2 2 1 2 0 0
运行时间:19ms
1 class Solution { 2 public: 3 int singleNumber(vector<int>& nums) { 4 const int len = sizeof(int) * 8; 5 int times[len] = {0}; 6 int result = 0; 7 8 for(int i = 0; i < len; i++){ 9 for(int j = 0; j < nums.size(); j++){ 10 times[i] += (nums[j] >> i) & 1; 11 } 12 result += (times[i] % 3) << i; 13 } 14 return result; 15 } 16 };
标签:
原文地址:http://www.cnblogs.com/amazingzoe/p/4508773.html