Loading

【leetcode】35. Search Insert Position

Given a sorted array of distinct integers 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 must write an algorithm with O(log n) runtime complexity.

Example 1:

Input: nums = [1,3,5,6], target = 5
Output: 2

1、排好序的数组、时间复杂度限制O(logn),明眼人都能看出需要用到二分法,这道题要稍微注意一下最后插入数据的位置。
class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        // 二分法的检索方法 时间复杂度才是o(logn)
        int left=0,right=nums.size()-1,mid=0;
        while(left<right){
            mid=(left+right)/2;
            if(nums[mid]<target){
                left=mid+1;
                
            }
            else if(nums[mid]>target){
                right=mid-1;
                
            }
            else{
                return mid; //找到相同的元素直接返回
            }
            
        }
        return target>nums[left]? left+1:left; //否则需要判断一下元素具体插入位置
        
    }
};

 




posted @ 2021-11-26 15:19  aalanwyr  阅读(25)  评论(0编辑  收藏  举报