您的位置:首页 > 其它

leetcode 99: Search Insert Position

2013-03-04 12:05 375 查看
SearchInsertPositionMar
3'12

Givenasortedarrayandatargetvalue,returntheindexifthetargetisfound.Ifnot,returntheindexwhereitwouldbeifitwereinsertedinorder.

Youmayassumenoduplicatesinthearray.

Herearefewexamples.

[1,3,5,6]
,
5→2

[1,3,5,6]
,
2→1

[1,3,5,6]
,
7→4

[1,3,5,6]
,
0→0

publicclassSolution{

publicintsearchInsert(int[]A,inttarget){

//StarttypingyourJavasolutionbelow

//DONOTwritemain()function

intlow=0,high=A.length-1,mid=low+(high-low)/2;

while(low<=high){

if(A[mid]==target)returnmid;

elseif(A[mid]<target){

low=mid+1;

}else{

high=mid-1;

}

mid=low+(high-low)/2;

}

returnmid;

}

}


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