[LeetCode] 35. Search Insert Position 搜索插入位置


 

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

 

這道題基本沒有什么難度,實在不理解為啥還是 Medium 難度的,完完全全的應該是 Easy 啊(貌似現在已經改為 Easy 類了),三行代碼搞定的題,只需要遍歷一遍原數組,若當前數字大於或等於目標值,則返回當前坐標,如果遍歷結束了,說明目標值比數組中任何一個數都要大,則返回數組長度n即可,代碼如下:

 

解法一:

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 二分搜索法小結 中第二類 - 查找不小於目標值的數,參見代碼如下:

 

解法二:

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

 

類似題目:

First Bad Version

 

參考資料:

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

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM