# LeetCode Search Insert Position

LeetCode Search Insert Position
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are 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

```class Solution {
public:
int findPos(vector<int>& nums, int s, int t, int target) {
if (s == t) {
if (nums[s] >= target)return s;
else return s + 1;
}
else if(s>t){ // caution!
return t + 1;
}
else {
int m = (s + t) / 2;
if (nums[m] == target)return m;
else if (nums[m] > target)return findPos(nums, s, m - 1, target);
else return findPos(nums, m + 1, t, target);
}
}
int searchInsert(vector<int>& nums, int target) {
return findPos(nums, 0, nums.size() - 1, target);
}
};
```

```class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int l = 0, r = nums.size() - 1;
while (l <= r) {
int m = l + (r - l) / 2;
if (nums[m] == target)return m;
if (nums[m] < target)l = m + 1;
else r = m - 1;
}
return l;
}
};
```

This site uses Akismet to reduce spam. Learn how your comment data is processed.