[LeetCode] Search Insert Position 搜尋插入位置

Grandyang發表於2015-04-09

 

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.

Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

 

這道題基本沒有什麼難度,實在不理解為啥還是Medium難度的,完完全全的應該是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();
    }
};

 

當然,我們還可以用二分搜尋法來優化我們的時間複雜度,而且個人認為這種方法應該是面試官們想要考察的演算法吧,參見程式碼如下:

 

解法二:

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        if (nums.back() < target) return nums.size();
        int left = 0, right = nums.size() - 1;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) return mid;
            else if (nums[mid] < target) left = mid + 1;
            else right = mid;
        }
        return right;
    }
};

 

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

相關文章