35. Search Insert Position

35. Search Insert Position

My Submissions
Question
Total Accepted: 94638  Total Submissions: 256951  Difficulty: Medium

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

Subscribe to see which companies asked this question

Hide Tags
  Array Binary Search
Hide Similar Problems
  (E) First Bad Version

分析:

二分查找要插入的位置,注意每一步操作的意义以及截止条件

时间复杂度:O(lg(n))

空间复杂度:O(1)

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int low=0,high=nums.size()-1;
        while(low<=high)
        {
            int mid=(low+high)/2;
            if(nums[mid]<target)
                low=mid+1;//要插入的位置在mid的右边(这里代码写成不包括mid位置,但是实际上有可能就是这个位置,所以low=high时必须继续误差判断一次)
            if(nums[mid]>target)
                high=mid-1;//要插入的位置在mid的左边(与上面同理)
            if(nums[mid]==target)
                return mid;//找到了
        }
        return low;
    }
};

简单优化:

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int low=0,high=nums.size()-1;  
        //本处属于极端情况处理,算是一种优化吧
        if(target > nums[high])
            return high+1;
        if(target < nums[low])
            return low;   
        //优化截止,开始查找在中间的插入位置
        while(low<=high)  
        {  
            int mid=(low+high)/2;  
            if(nums[mid]<target)  
                low=mid+1;//要插入的位置在mid的右边(这里代码写成不包括mid位置,但是实际上有可能就是这个位置,所以low=high时必须继续误差判断一次)  
            if(nums[mid]>target)  
                high=mid-1;//要插入的位置在mid的左边(与上面同理)  
            if(nums[mid]==target)  
                return mid;//找到了  
        }  
        return low; 
    }
};




最后吐槽:看了一下别人的解法,有一位小伙伴思路严谨,

他认为题目说了有序却没有说是正序还是逆序,所以分了两种情况判断。



注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/50734179

原作者博客:http://blog.csdn.net/ebowtang

本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895

你可能感兴趣的:(LeetCode,C++,算法,面试,二分法)