Skip to content

Instantly share code, notes, and snippets.

@jones
Created January 1, 2015 11:18
Show Gist options
  • Save jones/a9075f7f1644ea8c61ee to your computer and use it in GitHub Desktop.
Save jones/a9075f7f1644ea8c61ee to your computer and use it in GitHub Desktop.
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. Assume no duplicates in the array.
class Solution:
# @param A, a list of integers
# @param target, an integer to be inserted
# @return integer
def searchInsert1(self, A, target):
for i,val in enumerate(A):
if target <= val:
return i
return len(A)
def searchInsert2(self, A, target):
imin, imax = 0, len(A)-1
while imax >= imin:
imid = (imax - imin) // 2 + imin
if target == A[imid]:
return imid
elif target < A[imid]:
imax = imid - 1
elif target > A[imid]:
imin = imid + 1
return imin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment