题目
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.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
题意
很简单的题目,注意程序出现数组为空的情况。
C++语言
class Solution {
public:
int searchInsert(vector<int>& nums, int target)
{
//长度为0或者小于数组的最小值
if(nums.size() == 0 ||nums[0] >=target)
return 0;
//大于数组的最大值
if(target >nums[nums.size()-1])
return nums.size();
for(int i=1; i<nums.size(); i++)
{
if(target > nums[i-1] &&target<=nums[i])
return i;
}
}
};
Python语言
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
n = len(nums)
if n == 0 or target <= nums[0]:
return 0
if target > nums[n-1]:
return n
for index in range(1,n):
if target > nums[index-1] and target <= nums[index]:
return index