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. Assume that the target value is found in the array. Returns the position designator for this target value. If it is not found, it returns the position designator when the target value is inserted into the array.
You can if there are no repeating 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:
A two-point search is possible.
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>
[Leetcode][java] Search Insert Position