Chinaunix首页 | 论坛 | 博客
  • 博客访问: 255937
  • 博文数量: 170
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1709
  • 用 户 组: 普通用户
  • 注册时间: 2014-05-06 18:01
文章分类

全部博文(170)

文章存档

2016年(11)

2015年(130)

2014年(29)

分类: Java

2015-04-06 13:34:32

//Single Number II Total Accepted: 45470 Total Submissions: 131046 My Submissions Question Solution 
//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?



解法一:
        int 数据共有32位,可以用32变量存储 这 N 个元素中各个二进制位上  1  出现的次数,最后 在进行 模三 操作,如果为1,那说明这一位是要找元素二进制表示中为 1 的那一位。代码如下:
  1. class Solution {  
  2. public:  
  3.     int singleNumber(int A[], int n) {  
  4.         int bitnum[32]={0};  
  5.         int res=0;  
  6.         for(int i=0; i<32; i++){  
  7.             for(int j=0; j
  8.                 bitnum[i]+=(A[j]>>i)&1;  
  9.             }  
  10.             res|=(bitnum[i]%3)<
  11.         }  
  12.         return res;  
  13.     }  
  14. };  

时间:O(32*N),这是一个通用的解法,如果把出现3次改为 k 次,那么只需模k就行了。
解法二
public class SingleNumberTwo {
 public int singleNumber(int[] A) {
       int one=0,two=0,three=0;
       for(int i=0;i         two|=one&A[i];
        one^=A[i];
        three=one&two;
        one=one&~three;
        two=two&~three;
       }
       return one;
   }
}

阅读(336) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~