LeetCode-Search Insert Position的一种算法
题目链接:https://leetcode.com/problems/search-insert-position/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 be if it were inserted in order.
You may assume no duplicates in the array.
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
本题给出一个顺序数组以及一个目标数,要求我们找出目标数在顺序数组中的位置,若数组不存在该数,则给出该数在该数组中的插入位置。
由于数组中的数据一开始就是顺序排列的,所以只需要只需要遍历该数组,找出大于或等于目标数的数,随后返回该数位置即可。
于是代码如下:
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
for (int i = 0; i < nums.size(); i++) {
if (nums[i] >= target) {
return i;
}
}
return nums.size();
}
};
整个算法难度不大,只要理解题目的要求,随后转换为更直观的表述即可。