数组A中,除了某一个数字x之外,其他数字都出现了三次,而x出现了一次。请给出最快的方法,找到x
2016-07-17 20:21
471 查看
数组A中,除了某一个数字x之外,其他数字都出现了三次,而x出现了一次。请给出最快的方法,找到x。
2013-09-07 19:57 1365人阅读 评论(3) 收藏 举报分类:
算法(129)
ACM/POJ/PAT/九度(129)
版权声明:本文为博主原创文章,未经博主允许不得转载。
数组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?
#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;
}
相关文章推荐
- 简单的四则运算
- 数的奇偶性
- ACMer博客瀑布流分析
- ACM程序设计大赛题目分类
- 2015年acm国内排名
- 计算字符串最后一个单词长度
- ACM网址
- 1272 小希的迷宫
- 1272 小希的迷宫
- hdu 1250 大数相加并用数组储存
- 矩阵的乘法操作
- 蚂蚁爬行问题
- 蚂蚁爬行问题
- 求两个数的最大公约数【ACM基础题】
- 打印出二进制中所有1的位置
- 杭电题目---一只小蜜蜂
- HDOJ 1002 A + B Problem II (Big Numbers Addition)
- 初学ACM - 半数集(Half Set)问题 NOJ 1010 / FOJ 1207
- 初学ACM - 组合数学基础题目PKU 1833
- POJ ACM 1002