Search Insert Position - LeetCode
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.
Example 1:
Input: nums = [1,3,5,6], target = 5
Output: 2
Example 2:
Input: nums = [1,3,5,6], target = 2
Output: 1
Example 3:
Input: nums = [1,3,5,6], target = 7
Output: 4
Constraints:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums
contains distinct values sorted in ascending order.-104 <= target <= 104
Solution
class Solution {
func searchInsert(_ nums: [Int], _ target: Int) -> Int {
var low = 0
var high = nums.count - 1
var mid: Int = 0
var value = 0
if nums[0] > target {
return 0
} else if nums[nums.count - 1] < target {
return nums.count
}
while(low <= high) {
mid = (low + high) / 2
if nums[mid] == target {
return mid
} else if nums[mid] < target {
low = mid + 1
value = low
} else if nums[mid] > target {
high = mid - 1
value = high
}
}
if value >= 0 {
if nums[value] > target {
return value
} else {
return value + 1
}
}
return 0
}
}