题目
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
思考
遍历一次即可找到合适位置,可用二分法。
题目并没有讲明排好序的array是升序还是降序,可以通过对比前两个元素来确定。
答案
c++
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
if (nums[0] == target || nums[0] > target) return 0;
//if (nums[nums.size()] == target) return nums.size() - 1;
if (nums[nums.size() - 1] < target) return nums.size();
for (int i = 1; i < nums.size(); i++) {
if (nums[i] == target) {
return i;
} else {
if (nums[i - 1] < target && nums[i] > target) {
return i;
}
}
}
}
};