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
Problem solving idea One:
Binary Lookup, note the boundary condition, Java implementation is as follows:
static public int Searchinsert (int[] nums, int. target) {int left = 0, right = Nums.length-1;while (left <= right) {if (target = = nums[(left + right)/2]) return (left + right)/2;else if (Target < nums[(left + right)/2]) {if (left + right)/2-1 < left) return target > Nums[left]? Left + 1:left;if (Target > nums[(left + right)/2-1]) return (left + right)/2;if (target = = nums[(left + right)/ 2-1]) return (left + right)/2-1;right = (left + right)/2-1;} else {if (left + right)/2 + 1 > right) return to target > Nums[right]? Right + 1:right;if (target <= nums[ + right)/2 + 1]) return (left + right)/2 + 1;left = (left + right)/2 + 1;}} return right;}
Two ways to solve problems:
With the same two-point approach, there are some ways to reduce the amount of code that Java implements:
static public int Searchinsert (int[] nums, int target) {int left = 0, right = nums.length-1; while (left < right) { if (nums[(right + left)/2] < target) left = (right + left)/2 + 1; else Right = (right + left)/2; } return Nums[left] >= target? Left:left + 1; }
Java for Leetcode 035 Search Insert Position