leetcode刷题记录24

介绍

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

思路1

暴力解决

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if (nums==[]) or (nums[0]>target):
return 0
elif nums[-1]<target:
return len(nums)
else:
for i in range(len(nums)):
if nums[i]==target:
return i
elif (nums[i]<target) and (nums[i+1]>target):
return i+1

思路2

递归

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if (nums==[]) or (nums[0]>target):
return 0
elif nums[-1]<target:
return len(nums)
else:
return Solution.search(self,nums,target,0,len(nums)-1)
def search(self,nums,target,left,right):
if nums[left]==target:
return left
elif nums[right]==target:
return right
elif right-left==1:
return right
else:
if nums[(left+right)/2]<=target:
return self.search(nums,target,(left+right)/2,right)
elif nums[(left+right)/2]>target:
return self.search(nums,target,left,(left+right)/2)