[LeetCode]Single Number II

本文介绍了一种不使用额外内存的算法,用于找出数组中仅出现一次的整数,所有其他整数都出现三次。

题目说明

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?

思路

之前在Quora上看到一个用两个变量ones和twos分别统计1和2出现的次数来模拟“三进制”的方法。这次在网上又看到另一种解法也很不错,用一个长度为32的数组来统计每个位上1出现的次数,次数总和为3的倍数表明我们要求的数在该位是0,否则为1.

 

代码

public int singleNumber2(int[] A)
     {
         /* 注释内为用ones和twos统计1和2出现次数的解法
int ones=0,twos=0;
int n=A.length; //int result=A[0]; for(int i=0;i<n;i++) { int tmp=ones; ones=(tmp^A[i])&(~twos); twos=(tmp&A[i])|(twos&(~A[i])); } return ones; */ int[] count=new int[32]; for(int i=0;i<A.length;i++) { int num=A[i]; for(int j=0;j<32;j++) { if((num&(1<<j))!=0) count[j]++; } } int ans=0; for(int i=0;i<32;i++) { if(count[i]%3!=0) ans+=1<<i; } return ans; }

 

 

 

转载于:https://www.cnblogs.com/developerY/p/SingleNumber2.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值