Title Description:
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 Ideas:
A binary search is used to return the value of the position when it appears equal; otherwise the result is right < Left; This indicates that there are two cases in the previous loop: 1, the mid position is greater than target, then right = mid-after the last loop 1, so the position of the insertion must be right + 1 position, 2, the mid position value is less than target, then left = mid + 1 after the last loop, so the inserted position must be right + 1. In summary, the code looks like this:
The code is as follows:
public class Solution {public static int Searchinsert (int[] nums, int target) {int left, right, Mid;left = 0;right = Nums.length-1;while (left <= right) {mid = (left + right)/2;if (nums[left] = = target) return left;if (nums[right] = = Target) return right;if (Nums[mid] = target) return mid;if (Nums[mid] > target) right = Mid-1;else if (Nums[mid] < Target) left = mid + 1;} return right + 1;}}
Java [Leetcode 35]search Insert Position