首页 > 其他 > 详细

Single Number II

时间:2015-05-16 23:08:02      阅读:146      评论:0      收藏:0      [点我收藏+]

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 };

 

Single Number II

原文:http://www.cnblogs.com/amazingzoe/p/4508773.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!