📣 黑五价提前开抢|VIP一年通行证5折,蓝莓、Offer多多同步特惠
查看: 2612| 回复: 4
跳转到指定楼层
上一主题 下一主题
收起左侧

Google: Find the sole number in triple number array

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
You are given an array that contains integers. The integers content is such that
every integer occurs 3 times in that array leaving one integer that appears only once
Fastest way to find that single integer

-- not using any external memory (except a few trivial variables).
eg: [2,1,4,5,1,4,2,2,4,1]

上一篇:Amazon : Print palindrome nature number
下一篇:Google : Design a class to get average area of sub rectangle in O(1)
🔗
 楼主| wwwyhx 2011-7-19 21:33:08 | 只看该作者
全局:
You are given an array that contains integers. The integers content is such that
every integer occurs 3 times in that array leaving one integer that appears only once
Fastest way to find that single integer

-- not using any external memory (except a few trivial variables).
eg: [2,1,4,5,1,4,2,2,4,1]
wwwyhx 发表于 2011-7-15 16:04



    假设所有的数都有相同重复的3个,那么如果以int a[32]来记录所有数对应位的1的总合,那么数组a里每个元素都可以被3整除。

如果想讨巧,可以用一个int数来标记,可以被3整除的位就是1,反之是0, 那么最后遍历完数组后这个int数就是要求的数

  1. int GetSole(int a[], int n)
  2. {
  3.         assert(a && n > 0 && n%3 == 1);

  4.         int one = 0;
  5.         int two = 0;
  6.         int three = 0;
  7.         int mask = 0;

  8.         for (int i = 0; i < n; i++)
  9.         {
  10.                 int nTmp1 = one;
  11.                 int nTmp2 = two;
  12.                 int nTmp3 = three;

  13.                 one &= ~a[i];
  14.                 one |= a[i] & (~mask);
  15.                 one |= (nTmp3 & a[i]);

  16.                 two &= ~a[i];
  17.                 two |= (nTmp1 & a[i]);

  18.                 three &= ~a[i];
  19.                 three |= (nTmp2 & a[i]);
  20.                
  21.                 mask |= a[i];
  22.         }

  23.         return one;
  24. }
复制代码
回复

使用道具 举报

🔗
lambda2fei 2012-9-3 13:53:50 | 只看该作者
全局:
那楼主我问你一个扩展题:如果所有数都出现了1次,只有一个数出现2次,该怎么做?O(n)能解决吗?
回复

使用道具 举报

🔗
CStick75 2012-9-6 22:40:06 | 只看该作者
全局:
lambda2fei 发表于 2012-9-3 13:53
那楼主我问你一个扩展题:如果所有数都出现了1次,只有一个数出现2次,该怎么做?O(n)能解决吗?

表示还有一个扩展的,所有数都出现了k次,只有一个数出现了不到k次,O(1)的空间找出这个数
回复

使用道具 举报

🔗
lambda2fei 2012-9-9 14:51:22 | 只看该作者
全局:
CStick75 发表于 2012-9-6 22:40
表示还有一个扩展的,所有数都出现了k次,只有一个数出现了不到k次,O(1)的空间找出这个数

这个好办,按位模k即可,但是若反过来,所有数都出现k次,一个数出现了多于k次,要怎么做呢?就如我说的那题那样。当然排除所有数都出现偶数次一个数出现奇数次的情况。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表