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: 2Example 2:
Input: [1,3,5,6], 2 Output: 1Example 3:
Input: [1,3,5,6], 7 Output: 4Example 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:今天的编程直接是用的白板,属于一个小小的进步,以后能用白板用白板,思路异常的清晰