Title:
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
Test Instructions:
Given an ordered array and a target value, if the target value is found in the array, the position label of the target value is returned. If not found, returns the position label of the target value when it is inserted into the array.
You can assume that there are no duplicate elements in the array.
Here are some 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
Algorithm Analysis:
Two-point search can be. Directly on the code
AC Code:
<span style= "FONT-SIZE:12PX;" >public class Solution {public int searchinsert (int[] A, int target) { int i = 0; int j = a.length-1; while (i <= j) { int mid = (int) ((i + j)/2); if (a[mid] = = target) return mid; else if (A[mid] > target) j = mid-1; else i = mid + 1; } return i; }} </span>
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] Search Insert Position