1. 程式人生 > >leetcode第三題35:search insert position

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

 

今天這一題比較簡單,我用了一個遞迴就解決了,當然用迴圈遍歷也能解決,但是遞迴比較快。

程式碼執行效率打敗了100%的C++

static const int _ = []() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    return 0;
}();


class Solution {
    
public:
    int n;
    Solution(){
        n=0;
    }
    int searchInsert(vector<int>& nums, int target) {
        if(target<nums[0])
            return 0;
        if(target == nums[n])
            return n;
        if(target >nums[n-1]&&target<nums[n])
            return n;
        if(n==nums.size()-1)
            return n+1;
        n++;
        return searchInsert(nums,target);
    }
};

PS:今天的程式設計直接是用的白板,屬於一個小小的進步,以後能用白板用白板,思路異常的清晰