题目描述
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
解题思路
这个题的思路很简单就是直接遍历数组,用数组的每个元素跟 target 对比, 比较有技巧的一点是, 我们可以判断如果某个元素大于等于 target 时,就可以确定 target 在这个位置, 思路如下: 当 item=target 时, 结果确实就是 item 的位置 当第一个 item>target 时, 我们确实需要将 target 放在 item 的位置, item 后移,所以结果也是 item 的位置 当 item target 的值
时间复杂度: O(n)
示例代码
func searchInsert(_ nums: [Int], _ target: Int) -> Int {
var index = 0
for i in 0..<nums.count {
if (nums[i] >= target) {
return i
}else {
index = i + 1
}
}
return index
}