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.html
You may assume no duplicates in the array.git
Example 1:github
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
这道题基本没有什么难度,实在不理解为啥仍是 Medium 难度的,完彻底全的应该是 Easy 啊(貌似如今已经改成 Easy 类了),三行代码搞定的题,只须要遍历一遍原数组,若当前数字大于或等于目标值,则返回当前坐标,若是遍历结束了,说明目标值比数组中任何一个数都要大,则返回数组长度n便可,代码以下:post
解法一:优化
class Solution { public: int searchInsert(vector<int>& nums, int target) { for (int i = 0; i < nums.size(); ++i) { if (nums[i] >= target) return i; } return nums.size(); } };
固然,咱们还能够用二分搜索法来优化时间复杂度,并且我的认为这种方法应该是面试官们想要考察的算法吧,属于博主以前的总结帖 LeetCode Binary Search Summary 二分搜索法小结 中第二类 - 查找不小于目标值的数,参见代码以下:url
解法二:spa
class Solution { public: int searchInsert(vector<int>& nums, int target) { if (nums.back() < target) return nums.size(); int left = 0, right = nums.size(); while (left < right) { int mid = left + (right - left) / 2; if (nums[mid] < target) left = mid + 1; else right = mid; } return right; } };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/35
相似题目:
参考资料:
https://leetcode.com/problems/search-insert-position/
https://leetcode.com/problems/search-insert-position/discuss/15372/Simple-Java-solution
https://leetcode.com/problems/search-insert-position/discuss/15080/My-8-line-Java-solution