Search Insert Position
题目来自leetcode Array部分
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.
Example 1:
Input: [1,3,5,6], 5
Output: 2
Example 2:
Input: [1,3,5,6], 2
Output: 1
Example 3:
Input: [1,3,5,6], 7
Output: 4
Example 4:
Input: [1,3,5,6], 0
Output: 0
解题思路
题目没有限制运行时间,可以通过遍历一遍数组解决这个问题
- 设数组大小为n,从nums[0]开始,若target<=nums[0],返回0
- 否则开始遍历数组,若找到i,target等于nums[i],返回i;若target大于nums[i],target小于nums[i+1],并且i小于n-1,返回i+1
- 还未找到则返回n
代码块
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
if(nums.size() < 1) return 0;
if(target <= nums[0]) return 0;
for(int i = 0; i < nums.size(); i++){
if(nums[i] == target) return i;
if(nums[i] < target && target < nums[i+1] && i < nums.size()-1)
return i+1;
}
if(nums[nums.size()-1] < target) return nums.size();
}
};