算法分析與設計——LeetCode Problem.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.

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


問題分析及思路

這是一道Easy難度的題,題目大概就是向一個有序vector數組裏插入一個數,問這個數應該插在哪裏。
最直接的就是遍歷一次,算法時間複雜度是O(n)。
但是一定會有更方便的算法,我從快速排序的思路中找到了以下算法,將時間複雜度簡化到了O(log n)

1.設一個i爲0,j爲數組長度減1,mid爲(i+j)/2。
2.當i<=j時,將vector數組中的第mid個與目標數比較大小,若大於目標數,則j=mid-1,若小於目標數,則i=mid+1;若等於目標數,則返回mid。
3.i>j時,返回i。

算法比較簡單,這裏不再做更多分析。


具體代碼

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int i = 0, j = nums.size() - 1;
        int mid = (i + j) / 2;
        while (i <= j) {
            if(nums.at(mid) > target) {
                j = mid - 1;
                mid = (i + j) / 2;
            }
            if(nums.at(mid) < target) {
                i = mid + 1;
                mid = (i + j) / 2;
            }
            if(nums.at(mid) == target) {
                return mid;
            }
        }
        return i;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章