[leetcode] Single Number II
2015-06-18 22:28
309 查看
From : https://leetcode.com/problems/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?
Solution 1:
Solution 2:
Solution 3:
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?
Solution 1:
class Solution { public: int singleNumber(vector<int> nums) { int bitnum[32]={0}; int res=0; for(int i=0; i<32; i++){ for(int j=0, n=nums.size(); j<n; j++){ bitnum[i]+=(nums[j]>>i)&1; } res|=(bitnum[i]%3)<<i; } return res; } };
Solution 2:
class Solution2 { public: int singleNumber(vector<int>& nums) { int ans = 0, posi; for(int i=0; i<32; i++) { posi = 0; for(int j=0, size=nums.size(); j<size; j++) { posi += (nums[j]>>i)&1; } ans |= (posi%3)<<i; } return ans; } };
public class Solution { public int singleNumber(int[] nums) { if(nums == null || nums.length == 0) { return 0; } int a = 0; for(int I=0; I<32; ++I) { int n = 0; int F = 1<<I; for(int i=0; i<nums.length; ++i) { if((nums[i]&F) != 0) { // 必须不等于0,>0 <0对于正负数的情况会出现错误 ++n; } } if(n%3 == 1) { a |= F; } } return a; } }
Solution 3:
class Solution { public: int singleNumber(vector<int>& nums) { // ont %3为1的积累,two %3为2, three %3为0 int one=0, two=0, three=0; for(int i=0, n=nums.size(); i<n; i++){ // %3为1的积累和这次数的1,即%3为2的积累, 与上次积累%3为2的或为这次积累量 two |= one & nums[i]; // 这次与前一次%3为1的积累异或,为当前%3为1的积累 one ^= nums[i]; // %3为0的积累 three = one & two; // 将出现三次的置为0 one &= ~three; two &= ~three; } return one; } };
相关文章推荐
- css line-height详解
- tomcat 架构分析 zu
- [leetCode] Contains Duplicate
- 今天在csdn看到一博主今年大三,初中就喜欢上编程,学习了各种知识,初中…挺震惊。不禁细数我的编程史,挺有感。
- 为什么一个JavaScript数组splice方法,网页环境、node环境、java8环境等不一样呢
- hdu 1527
- 内存的静态分配和动态分配的区别
- 用PowerShell查找一个进程的父进程
- 位的与运算与取模
- mac上搭建python+selenium2的环境
- Spring REST 异常处理
- The Pilots Brothers' refrigerator - poj 2965
- connect to windows with rdp
- [leetCode] Combination Sum III
- 求和:1+11+111,或者2+22+……
- html做的word申请表(样式)
- Oracle启动em问题
- E3-1260L (8M Cache, 2.40 GHz) E3-1265L v2 (8M Cache, 2.50 GHz)
- 我总结的git命令指南。
- Dynamic Programming | Set 4 (Longest Common Subsequence)