码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-Single Number II

时间:2017-01-16 19:57:53      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:class   number   int   memory   should   nbsp   single   run   1出现的次数   

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?

数组中数字均出现三次,只有一个只出现一次,找出它。

思路:two表示出现两次的数字,one表示出现一次的数字,three表示出现3次的数字。

对于除出现一次之外的所有的整数,其二进制表示中每一位1出现的次数是3的整数倍,将所有这些1清零,剩下的就是最终的数。用ones记录到当前计算的变量为止,二进制1出现“1次”(mod 3 之后的 1)的数位。用twos记录到当前计算的变量为止,二进制1出现“2次”(mod 3 之后的 2)的数位。当ones和twos中的某一位同时为1时表示二进制1出现3次,此时需要清零。即用二进制模拟三进制计算。最终ones记录的是最终结果。

 1 public class Solution {
 2     public int singleNumber(int[] A) {
 3         int one=0,two=0,three=0;
 4         for(int i=0;i<A.length;i++){
 5             two|=one&A[i];
 6             one^=A[i];
 7             three=~(one&two);
 8             one&=three;
 9             two&=three;
10         }
11         return one;
12     }
13 }

 

leetcode-Single Number II

标签:class   number   int   memory   should   nbsp   single   run   1出现的次数   

原文地址:http://www.cnblogs.com/zl1991/p/6290738.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!