题目:
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
示例 1:
输入: [1,3,5,6], 5
输出: 2
示例 2:
输入: [1,3,5,6], 2
输出: 1
示例 3:
输入: [1,3,5,6], 7
输出: 4
我自己的解答是一只在用if判断啦,附上代码:
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
a = False
for i in range(len(nums)): # 判断target是否在数组中
if nums[i] == target:
a = True
if a == True:
return nums.index(target)
elif a == False:
for i in range(len(nums)):
if target < nums[0]: # 三种情况
nums.insert(0,target)
break
elif target > nums[len(nums)-1]:
nums.append(target)
break
elif (nums[i] < target) and (nums[i+1] > target):
nums.insert(i+1,target)
break
return nums.index(target)