您的位置:首页 > 其它

lintcode-medium-Nuts & Bolts Problem

2016-04-03 13:18 232 查看
Givenasetofnnutsofdifferentsizesandnboltsofdifferentsizes.Thereisaone-onemappingbetweennutsandbolts.Comparisonofanuttoanothernutorabolttoanotherboltisnotallowed.Itmeansnutcanonlybecomparedwithboltandboltcanonlybecomparedwithnuttoseewhichoneisbigger/smaller.

Wewillgiveyouacomparefunctiontocomparenutwithbolt.

Example

Givennuts=
['ab','bc','dd','gg']
,bolts=
['AB','GG','DD','BC']
.

Yourcodeshouldfindthematchingboltsandnuts.

oneofthepossiblereturn:

nuts=
['ab','bc','dd','gg']
,bolts=
['AB','BC','DD','GG']
.

wewilltellyouthematchcomparefunction.Ifwegiveyouanothercomparefunction.

thepossiblereturnisthefollowing:

nuts=
['ab','bc','dd','gg']
,bolts=
['BC','AA','DD','GG']
.

Soyoumustusethecomparefunctionthatwegivetodothesorting.

Theorderofthenutsorboltsdoesnotmatter.Youjustneedtofindthematchingboltforeachnut.




/**
*publicclassNBCompare{
*publicintcmp(Stringa,Stringb);
*}
*Youcanusecompare.cmp(a,b)tocomparenuts"a"andbolts"b",
*if"a"isbiggerthan"b",itwillreturn1,elseiftheyareequal,
*itwillreturn0,elseif"a"issmallerthan"b",itwillreturn-1.
*When"a"isnotanutor"b"isnotabolt,itwillreturn2,whichisnotvalid.
*/
publicclassSolution{
/**
*@paramnuts:anarrayofintegers
*@parambolts:anarrayofintegers
*@paramcompare:ainstanceofComparator
*@return:nothing
*/
publicvoidsortNutsAndBolts(String[]nuts,String[]bolts,NBComparatorcompare){
//writeyourcodehere

if(nuts==null||nuts.length==0||bolts==null||bolts.length==0||nuts.length!=bolts.length)
return;

sort(nuts,bolts,0,nuts.length-1,compare);

return;
}

publicvoidsort(String[]nuts,String[]bolts,intstart,intend,NBComparatorcompare){

if(start>=end)
return;

intpartition=partition(nuts,bolts[end],start,end,compare);
partition(bolts,nuts[partition],start,end,compare);

sort(nuts,bolts,start,partition-1,compare);
sort(nuts,bolts,partition+1,end,compare);

return;
}

publicintpartition(String[]array,Stringpivot,intstart,intend,NBComparatorcompare){

if(start>=end)
returnstart;

intleft=start;
intright=end;

Stringpivot_mirror=null;

for(inti=start;i<=end;i++)
if(compare.cmp(array[i],pivot)==0||compare.cmp(pivot,array[i])==0){
pivot_mirror=array[i];
break;
}

while(true){
while(left<right&&((compare.cmp(array[left],pivot)==-1)||(compare.cmp(pivot,array[left])==1)))
left++;

while(left<right&&((compare.cmp(array[right],pivot)==1)||compare.cmp(pivot,array[right])==-1))
right--;

if(left==right)
break;

swap(array,left,right);
}
array[left]=pivot_mirror;

returnleft;
}

publicvoidswap(String[]array,inti,intj){
Stringtemp=array[i];
array[i]=array[j];
array[j]=temp;

return;
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: