有做过CMU编程测试的筒子么
Azero-indexedarrayAconsistingofNintegersisgiven.AnequilibriumindexofthisarrayisanyintegerPsuchthat0≤P<Nandthesumofelementsoflowerindicesisequaltothesumofelementsofhigherindices,i.e.
A[0]+A[1]+...+A[P−1]=A[P+1]+...+A[N−2]+A[N−1]..鐣欏鐢宠璁哄潧-涓€浜╀笁鍒嗗湴
Sumofzeroelementsisassumedtobeequalto0.ThiscanhappenifP=0orifP=N−1.
Forexample,considerthefollowingarrayAconsistingofN=8elements:
A[0]=-1
A[1]=3
A[2]=-4
A[3]=5
A[4]=1
A[5]=-6.鐣欏璁哄潧-涓€浜�-涓夊垎鍦�
A[6]=2
A[7]=1
P=1isanequilibriumindexofthisarray,because:.链枃铡熷垱镊�1point3acres璁哄潧
A[0]=−1=A[2]+A[3]+A[4]+A[5]+A[6]+A[7]
P=3isanequilibriumindexofthisarray,because:
A[0]+A[1]+A[2]=−2=A[4]+A[5]+A[6]+A[7]
P=7isalsoanequilibriumindex,because:
A[0]+A[1]+A[2]+A[3]+A[4]+A[5]+A[6]=0
andtherearenoelementswithindicesgreaterthan7.
P=8isnotanequilibriumindex,becauseitdoesnotfulfillthecondition0≤P<N..1point3acres.com/bbs
Writeafunction:
intsolution(intA[],intN);
that,givenazero-indexedarrayAconsistingofNintegers,returnsanyofitsequilibriumindices.Thefunctionshouldreturn−1ifnoequilibriumindexexists..1point3acres缃�
Forexample,givenarrayAshownabove,thefunctionmayreturn1,3or7,asexplainedabove.
Assumethat:
Nisanintegerwithintherange[0..100,000];
eachelementofarrayAisanintegerwithintherange[−2,147,483,648..2,147,483,647].
Complexity:
expectedworst-casetimecomplexityisO(N);鏉ユ簮涓€浜�.涓夊垎鍦拌鍧�.
expectedworst-casespacecomplexityisO(N),beyondinputstorage(notcountingthestoragerequiredforinputarguments).
Elementsofinputarrayscanbemodified.
Copyright2009–2015byCodilityLimited.AllRightsReserved.Unauthorizedcopying,publicationordisclosureprohibited.
免责声明:本站部分内容转载于网络,其中内容仅代表作者个人观点,与本网无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。若有来源标注错误或侵犯了您的合法权益,请作者持权属证明与本网联系,我们将及时更正、删除,谢谢。
本站联系邮箱:599911198#qq.co m