Algorithm/Daily Coding Tests Challenge
[Leetcode] Easy : Search Insert Position
Jesip14
2021. 9. 5. 16:55
Description
Given a sorted array of distinct integers 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 must write an algorithm with O(log n) runtime complexity.
My solution
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
if target in nums:
return nums.index(target)
else:
nums.append(target)
return sorted(nums).index(target)
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
if target in nums:
return nums.index(target)
else:
for i, val in enumerate(nums):
if target < val:
return i
elif target > max(nums):
return len(nums)