【LeetCode】Search Insert Position
程序员文章站
2024-03-15 21:13:00
...
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
题意:给定一个有序数组,在其中找到给定的target,找到就返回它在数组中的下标,如果没有找到就返回target应该插入的位置的下标
C++:
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
auto it=find(nums.begin(),nums.end(),target);
int i=0;
if(it==nums.end()){
for(i=0;i<nums.size();i++){
if(nums[i]>target)break;
}
}else{
for(i=0;i<nums.size();i++)
if(nums[i]==target)break;
}
return i;
}
};
Python3:
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
if target in nums:
return nums.index(target)
else:
i=0
for index in range(len(nums)):
if nums[i]>target:
break
i+=1
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