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

本文介绍了一种高效算法来寻找数组中出现次数不同的元素,并提供了详细代码实现。

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

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

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

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

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

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

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

那么,三次出现清零呢?

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

现在:

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

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

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

具体代码:

#include<stdio.h>
#include<stdlib.h>
int find_num(int *num,int len)
{
    int i;
    int even=0;
    int odd=0;
    for(i=0;i<len;i++){
        even |= odd&num[i];//every postion which 1 appear is odd,1 is appear again,the count of 1 is even,set 1;
        odd ^= num[i];//every postion,when the count of 1 is odd, the location of postion is set 1;
        int is_three = (even&odd);//every postion,from even to odd , the 1 postion, 1 is appear three times;
        int three_to_zero = ~is_three;//the postion which 1 is appear thhree time back to 0;
        even &= three_to_zero;
        odd &= three_to_zero;
    }
    return odd;//is need return only appear two time ,return even;
}
int main()
{
   int num[]={8,8,8,1,1,1,3,4,3,3,5,5,7,5,7,7}; 
   int x=find_num(num,sizeof(num)/sizeof(int));
   printf("x=%d\n",x);
   return 0;
}






评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值