Topic:
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
Answer:
The problem is not difficult, but note the boundary conditions:
- Target value is less than or equal to a[0];
- A is an empty array;
- Target value is greater than all elements in A;
- Otherwise, is target value equal to a[i], or is it equal to a[i+1], or (A[i], a[i+1])?
Class Solution {public: int searchinsert (int a[], int n, int target) { if (n = = 0 | | A[0] >= target) return 0; if (A[n-1] < target) return n; int ans; for (int i = 0; i< n-1; i++) { if (a[i] = = target) { ans = i; } if (a[i+1] = = target) { ans = (i+1); } if (A[i] < target && a[i+1] > target) { ans = (i+1); } } return ans; };
"Leetcode from zero single brush" Search Insert Position