给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
python:
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
n = len(nums)
if n == 0:
return 0
for i in range(n):
if nums[i] >= target:
return i
elif i == (n - 1):
return n
C++:
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int n = nums.size();
if(n == 0) return 0;
for(int i = 0;i < n;i++){
if(nums[i] >= target) return i;
else if(i == (n - 1)) return n;
}
}
};