"035-search Insert Position (search Insert location)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"
Original Question
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would is if it were inserted in order.
Assume no duplicates in the array.
Here is few examples.
[1,3,5,6], 5 → 2[1,3,5,6], 2 → 1[1,3,5,6], 7 → 4[1,3,5,6], 0 → 0
Main Topic
Given a sorted array, and a specified value, if this value is found, returns the position of the value, if not found, returns the insertion position of this value in the array.
Assume that there are no duplicate elements in the array.
Thinking of solving problems
First, the most direct search algorithm, from left to right.
Second, the use of binary search algorithm.
Code Implementation
Algorithm implementation class (direct lookup)
publicclass Solution { publicintsearchInsert(intint target) { ifnull) { return -1; } int i; for0; i < A.length; i++) { if (A[i] >= target) { return i; } } return i; }}
Algorithm implementation Class (two-point lookup)
Public classSolution { Public int Searchinsert(int[] A,intTarget) {intMidintLo =0;inthi = A.length-1; while(Lo <= hi) {mid = lo + (hi-lo)/2;if(A[mid] = = target) {returnMid }Else if(A[mid] < target) {lo = mid +1; }Else{hi = mid-1; } }returnLo }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Direct algorithm
Binary search algorithm
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47079367"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java implementation" "035-search insert Position (search insert location)"