数组A中,除了某一个数字x之外,其他数字都出现了三次,而x出现了一次。请给出最快的方法,找到x

数组A中,除了某一个数字x之外,其他数字都出现了三次,而x出现了一次。请给出最快的方法,找到x。

  1365人阅读  评论(3)  收藏  举报
  分类:
 
 

数组A中,除了某一个数字x之外,其他数字都出现了三次,而x出现了一次。请给出最快的方法,找到x。

这是@陈利人http://weibo.com/1915548291/A8jX24VyW#_rnd1378555193798出的一道题。

类似的:数组A中,除了某一个数字x之外,其他数字都出现了三次,而x出现了两次。请给出最快的方法,找到x。

这道题是:数组A中,除了某一个数字x之外,其他数字都出现了两次,而x出现了一次。请给出最快的方法,找到x。的变种。

思路:http://blog.csdn.net/zhu_liangwei/article/details/11074997和这道题有些区别。

现在重新来看关于这几种题目,关键是找出一种多次出现对应位清零的技术。

异或运算是两次出现清零。

那么,三次出现清零呢?

在两次出现的基础上改进:如有已经两次出现了,如果再出现,让么算3次出现。

现在:

某一位偶数次出现1,使用even记录,对应为置为1;

某一位奇数次出现1,使用odd奇数,对应为置为1;

上一次某位偶数出现1,这次奇数出现1,说明是第三次,使用is_three,对应位清零。

具体代码:

[cpp]  view plain  copy
 print ?
  1. #include<stdio.h>  
  2. #include<stdlib.h>  
  3. int find_num(int *num,int len)  
  4. {  
  5.     int i;  
  6.     int even=0;  
  7.     int odd=0;  
  8.     for(i=0;i<len;i++){  
  9.         even |= odd&num[i];//every postion which 1 appear is odd,1 is appear again,the count of 1 is even,set 1;  
  10.         odd ^= num[i];//every postion,when the count of 1 is odd, the location of postion is set 1;  
  11.         int is_three = (even&odd);//every postion,from even to odd , the 1 postion, 1 is appear three times;  
  12.         int three_to_zero = ~is_three;//the postion which 1 is appear thhree time back to 0;  
  13.         even &= three_to_zero;  
  14.         odd &= three_to_zero;  
  15.     }  
  16.     return odd;//is need return only appear two time ,return even;  
  17. }  
  18. int main()  
  19. {  
  20.    int num[]={8,8,8,1,1,1,3,4,3,3,5,5,7,5,7,7};   
  21.    int x=find_num(num,sizeof(num)/sizeof(int));  
  22.    printf("x=%d\n",x);  
  23.    return 0;  
  24. }  
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值