代码面试最常用的10大算法(五)
2014-04-23 14:34
459 查看
8.位操作符:
从一个给定的数n中找位i(i从0开始,然后向右开始)
例如,获取10的第二位:
典型的位算法:
FindSingleNumber
Theproblem:
Givenanarrayofintegers,everyelementappearstwiceexceptforone.Findthatsingleone.
从一个给定的数n中找位i(i从0开始,然后向右开始)
FindSingleNumber
Theproblem:
Givenanarrayofintegers,everyelementappearstwiceexceptforone.Findthatsingleone.
Thoughts
Thekeytosolvethisproblemisbitmanipulation.XORwillreturn1onlyontwodifferentbits.Soiftwonumbersarethesame,XORwillreturn0.Finallyonlyonenumberleft.
JavaSolution
publicclassSolution{ publicintsingleNumber(int[]A){ intx=0; for(inta:A){ x=x^a; } returnx; } } MaximumBinaryGap
Problem:GetmaximumbinaryGap.
Forexample,9′sbinaryformis1001,thegapis2.
Thoughts
Thekeytosolvethisproblemisthefactthatanintegerx&1willgetthelastdigitoftheinteger.
JavaSolution
publicclassSolution{ publicstaticintsolution(intN){ intmax=0; intcount=-1; intr=0; while(N>0){ //getrightmostbit&shiftright r=N&1; N=N>>1; if(0==r&&count>=0){ count++; } if(1==r){ max=count>max?count:max; count=0; } } returnmax; } publicstaticvoidmain(String[]args){ System.out.println(solution(9)); } }
9.概率
通常要解决概率相关问题,都需要很好地格式化问题,下面提供一个简单的例子:
算法:
结果:
10.组合和排列
组合和排列的主要差别在于顺序是否重要。
例1:
例2:
基于它们的一些常见算法
排列1
Givenacollectionofnumbers,returnallpossiblepermutations.
Forexample, [1,2,3]havethefollowingpermutations: [1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],and[3,2,1].
JavaSolution1
Wecangetallpermutationsbythefollowingsteps:
[1] [2,1] [1,2] [3,2,1] [2,3,1] [2,1,3] [3,1,2] [1,3,2] [1,2,3]
Loopthroughthearray,ineachiteration,anewnumberisaddedtodifferentlocationsofresultsofpreviousiteration.StartfromanemptyList.
publicArrayList<ArrayList<Integer>>permute(int[]num){ ArrayList<ArrayList<Integer>>result=newArrayList<ArrayList<Integer>>(); //startfromanemptylist result.add(newArrayList<Integer>()); for(inti=0;i<num.length;i++){ //listoflistincurrentiterationofthearraynum ArrayList<ArrayList<Integer>>current=newArrayList<ArrayList<Integer>>(); for(ArrayList<Integer>l:result){ //#oflocationstoinsertislargestindex+1 for(intj=0;j<l.size()+1;j++){ //+addnum[i]todifferentlocations l.add(j,num[i]); ArrayList<Integer>temp=newArrayList<Integer>(l); current.add(temp); //System.out.println(temp); //-removenum[i]add l.remove(j); } } result=newArrayList<ArrayList<Integer>>(current); } returnresult; } |
Wecanalsorecursivelysolvethisproblem.Swapeachelementwitheachelementafterit.
publicArrayList<ArrayList<Integer>>permute(int[]num){ ArrayList<ArrayList<Integer>>result=newArrayList<ArrayList<Integer>>(); permute(num,0,result); returnresult; } voidpermute(int[]num,intstart,ArrayList<ArrayList<Integer>>result){ if(start>=num.length){ ArrayList<Integer>item=convertArrayToList(num); result.add(item); } for(intj=start;j<=num.length-1;j++){ swap(num,start,j); permute(num,start+1,result); swap(num,start,j); } } privateArrayList<Integer>convertArrayToList(int[]num){ ArrayList<Integer>item=newArrayList<Integer>(); for(inth=0;h<num.length;h++){ item.add(num[h]); } returnitem; } privatevoidswap(int[]a,inti,intj){ inttemp=a[i]; a[i]=a[j]; a[j]=temp; } 排列2
Givenacollectionofnumbersthatmightcontainduplicates,returnallpossibleuniquepermutations.
Forexample, [1,1,2]havethefollowinguniquepermutations: [1,1,2],[1,2,1],and[2,1,1].
Thoughts
Basicidea:Foreachnumberinthearray,swapitwitheveryelementafterit.Toavoidduplicate,needtocheckitfirst.
JavaSolution
publicArrayList<ArrayList<Integer>>permuteUnique(int[]num){ ArrayList<ArrayList<Integer>>result=newArrayList<ArrayList<Integer>>(); permuteUnique(num,0,result); returnresult; } privatevoidpermuteUnique(int[]num,intstart,ArrayList<ArrayList<Integer>>result){ if(start>=num.length){ ArrayList<Integer>item=convertArrayToList(num); result.add(item); } for(intj=start;j<=num.length-1;j++){ if(containsDuplicate(num,start,j)){ swap(num,start,j); permuteUnique(num,start+1,result); swap(num,start,j); } } } privateArrayList<Integer>convertArrayToList(int[]num){ ArrayList<Integer>item=newArrayList<Integer>(); for(inth=0;h<num.length;h++){ item.add(num[h]); } returnitem; } privatebooleancontainsDuplicate(int[]arr,intstart,intend){ for(inti=start;i<=end-1;i++){ if(arr[i]==arr[end]){ returnfalse; } } returntrue; } privatevoidswap(int[]a,inti,intj){ inttemp=a[i]; a[i]=a[j]; a[j]=temp; } 排列顺序
Theset[1,2,3,…,n]containsatotalofn!uniquepermutations.
Bylistingandlabelingallofthepermutationsinorder,
Wegetthefollowingsequence(ie,forn=3):
"123" "132" "213" "231" "312" "321"
Givennandk,returnthekthpermutationsequence.
Note:Givennwillbebetween1and9inclusive.
Thoughts
Naivelyloopthroughallcaseswillnotwork.
JavaSolution1
publicclassSolution{ publicStringgetPermutation(intn,intk){ //initializeallnumbers ArrayList<Integer>numberList=newArrayList<Integer>(); for(inti=1;i<=n;i++){ numberList.add(i); } //changektobeindex k--; //setfactorialofn intmod=1; for(inti=1;i<=n;i++){ mod=mod*i; } Stringresult=""; //findsequence for(inti=0;i<n;i++){ mod=mod/(n-i); //findtherightnumber(curIndex)of intcurIndex=k/mod; //updatek k=k%mod; //getnumberaccordingtocurIndex result+=numberList.get(curIndex); //removefromlist numberList.remove(curIndex); } returnresult.toString(); } } |
publicclassSolution{ publicStringgetPermutation(intn,intk){ boolean[]output=newboolean[n]; StringBuilderbuf=newStringBuilder(""); int[]res=newint[n]; res[0]=1; for(inti=1;i<n;i++) res[i]=res[i-1]*i; for(inti=n-1;i>=0;i--){ ints=1; while(k>res[i]){ s++; k=k-res[i]; } for(intj=0;j<n;j++){ if(j+1<=s&&output[j]){ s++; } } output[s-1]=true; buf.append(Integer.toString(s)); } returnbuf.toString(); } }