Description
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:
1 | Input: [1,3,5,6], 5 |
Example 2:
1 | Input: [1,3,5,6], 2 |
Example 3:
1 | Input: [1,3,5,6], 7 |
Example 4:
1 | Input: [1,3,5,6], 0 |
Difficulty: Easy
Code:
1 | class Solution { |
题意
给定一个有序数组nums和一个目标值target,若数组中nums能找到target则返回下标,否则返回它应该放入的位置。数组中没有重复元素。
Solution 1
先把target大于或者小于nums所有数的情况解决掉,剩下就是在nums中进行二分查找。
若能找到则返回下标,若不能,则退出循环时left的位置即为应插入的位置。
1 | class Solution { |
时间复杂度: O()。
空间复杂度: O()。