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