Search Insert Position
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.
Example 1:
Input: [1,3,5,6], 5
Output: 2
Example 2:
Input: [1,3,5,6], 2
Output: 1
Example 3:
Input: [1,3,5,6], 7
Output: 4
Example 4:
Input: [1,3,5,6], 0
Output: 0
C语言
int searchInsert(int* nums, int numsSize, int target) {
for(int i=0;i<numsSize;i++){
if((nums[i]==target)||(nums[i]>target))
return i;
else if(nums[numsSize-1]<target)
return numsSize;
}
return 0;
}
Success
Details
Runtime: 4 ms, faster than 88.41% of C online submissions for Search Insert Position.
Memory Usage: 7 MB, less than 100.00% of C online submissions for Search Insert Position.
python3
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
for i in range(len(nums)):
if((nums[i]==target)or(nums[i]>target)):
return i
elif(nums[len(nums)-1]<target):
return len(nums)
Success
Details
Runtime: 52 ms, faster than 14.00% of Python3 online submissions for Search Insert Position.
Memory Usage: 13.7 MB, less than 5.11% of Python3 online submissions for Search Insert Position.
Next challenges: