forked from yingl/LintCodeInPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch_insert_position.py
More file actions
31 lines (30 loc) · 912 Bytes
/
search_insert_position.py
File metadata and controls
31 lines (30 loc) · 912 Bytes
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
26
27
28
29
30
31
# -*- coding: utf-8 -*-
class Solution:
"""
@param A : a list of integers
@param target : an integer to be inserted
@return : an integer
"""
def searchInsert(self, A, target):
# write your code here
if A:
start, end = 0, len(A)
while start < end:
mid = (start + end) / 2
if A[mid] < target:
start += 1
elif A[mid] > target:
end = mid
else:
break
# 判断mid位置
if A[mid] > target:
return mid
elif A[mid] < target:
return mid + 1
else:
# 等于的情况要找到第一个插入位置
for i in xrange(mid - 1, -1, -1):
if A[i] < target:
return i + 1
return 0