[LeetCode]Single Number II
2014-02-17 19:32
363 查看
题目说明
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?
思路
之前在Quora上看到一个用两个变量ones和twos分别统计1和2出现的次数来模拟“三进制”的方法。这次在网上又看到另一种解法也很不错,用一个长度为32的数组来统计每个位上1出现的次数,次数总和为3的倍数表明我们要求的数在该位是0,否则为1.代码
public int singleNumber2(int[] A) { /* 注释内为用ones和twos统计1和2出现次数的解法 int ones=0,twos=0; int n=A.length; //int result=A[0]; for(int i=0;i<n;i++) { int tmp=ones; ones=(tmp^A[i])&(~twos); twos=(tmp&A[i])|(twos&(~A[i])); } return ones; */ int[] count=new int[32]; for(int i=0;i<A.length;i++) { int num=A[i]; for(int j=0;j<32;j++) { if((num&(1<<j))!=0) count[j]++; } } int ans=0; for(int i=0;i<32;i++) { if(count[i]%3!=0) ans+=1<<i; } return ans; }
相关文章推荐
- FatMouse' Trade
- hdu-3308-LCIS 线段树
- HDU 1166 敌兵布阵
- HDU 1166 敌兵布阵
- 一个 fork 的面试题
- db2错误码整理
- 【几何+暴力】-CF-391D1-Supercollider
- powerpc开发板使用收获总结
- Sicily 1926
- UILabel
- J2EE——Jsp的学习
- js中call与apply用法
- Balanced Binary Tree
- 设计一个可以用<<和逗号输入矩阵的方案
- [Python]python学习笔记(一)——语法
- 【转】PHP怎么实现字符串翻转(包含中文汉字)
- 模视图转换
- Sicily 1930
- openwrt启动脚本分析
- Install Shield 脚本(总)