[leetcode]Search Insert Position
程序员文章站
2024-03-15 21:12:42
...
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
分析:
由于数组是排好序的,因此只要将要插入数字依次与数组内数字比较,大于等于要插入的数字时,其索引就是插入的位置
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int len = nums.size();
int i = 0;
for(i=0; i<len; i++)
{
if(nums[i] >= target)
break;
}
return i;
}
};
上一篇: 快速删除海量数据
下一篇: 组合问题之代表团出访
推荐阅读
-
【leetcode】35. Search Insert Position 给定数字插入有序数组的下标点
-
[leetcode]Search Insert Position
-
LeetCode: Search Insert Position
-
Search Insert Position -- LeetCode
-
【LeetCode】Search Insert Position
-
[Leetcode] -- Search Insert Position
-
LeetCode 34. 在排序数组中查找元素的第一个和最后一个位置 Find First and Last Position of Element in Sorted Array
-
【LeetCode 5296】All Elements in Two Binary Search Trees【Medium】【JAVA】
-
[leetcode] Insert Interval
-
LeetCode-34-Search for a Range