您的位置:首页 > 其它

Single Number

2015-07-29 23:44 405 查看
题目:

Givenanarrayofintegers,everyelementappearstwiceexceptforone.Findthatsingleone.

解法一:bitmanipulate

publicclassSolution{
publicintsingleNumber(int[]nums){
intans=0;
for(inti=0;i<nums.length;i++)ans^=nums[i];
returnans;

}
}


因为AXORA=0,且XOR运算是可交换的,于是,对于实例{2,1,4,5,2,4,1}就会有这样的结果:

(2^1^4^5^2^4^1)=>((2^2)^(1^1)^(4^4)^(5))=>(0^0^0^5)=>5


reference:http://www.powerxing.com/leetcode-single-number/


解法二:hashmap(reference:CleanCodeHandbook)


wecoulduseamaptokeeptrackofthenumberoftimesanelementapprears.Inasecondpass,wecouldextractthesinglenumberbyconsultingthehashmap.Asahashmapprovidesconstanttimelookup,theoverallcomplexityisO(n),wherenisthetotalnumberofelements.

publicintsingleNumber(int[]nums)
{
//usehashmap
Map<Integer,Integer>map=newHashMap<>();
for(intx:nums)
{
intcount=map.containsKey(x)?map.get(x):0;
map.put(x,count+1);
}
for(intx:nums)
{
if(map.get(x)==1)
{
returnx;
}
}

thrownewIllegalArgumentException("NoSingleElment");

}


解法三:Hashset(reference:cleancodehandbook)

Althoughthemapapproachworks,wearenottakingadvantageofthe"everyelementsapprearstwiceexceptone"property.Couldwedobetterinonepass?

Howaboutinsertingtheelementsintoasetinstead?Ifanelementalreadyexists,wediscardtheelementfromthesetknowingthatitwillnotappearagain.Afterthefirstpass,thesetmushcontainonlythesingleelement.

publicclassSolution{
publicintsingleNumber(int[]nums){
//usehashset
HashSet<Integer>set=newHashSet<>();
for(intx:nums)
{
if(set.contains(x))
{
set.remove(x);
}
else
{
set.add(x);
}
}

returnset.iterator().next();
}
}


set.iterator:

Thefollowingexampleshowstheusageofjava.util.HashSet.iterator()

packagecom.tutorialspoint;

importjava.util.*;

publicclassHashSetDemo{
publicstaticvoidmain(Stringargs[]){
//createhashset
HashSet<String>newset=newHashSet<String>();

//populatehashset
newset.add("Learning");
newset.add("Easy");
newset.add("Simply");

//createaniterator
Iteratoriterator=newset.iterator();

//checkvalues
while(iterator.hasNext()){
System.out.println("Value:"+iterator.next()+"");
}
}
}


Letuscompileandruntheaboveprogram,thiswillproducethefollowingresult.

Value:Learning
Value:Simply
Value:Easy


reference:
http://blog.csdn.net/kenden23/article/details/13625297http://www.programcreek.com/2012/12/leetcode-solution-of-single-number-in-java/http://www.tutorialspoint.com/java/util/hashset_iterator.htm
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: