LeetCode_Simple_35. Search Insert Position

2019.1.15

题目描述:

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

没啥讲的,就是一个简单的搜索算法。。。估计是为了考察二分查找。。

先来个常规的吧

解法一:

C++代码:

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

闲着无聊。。

解法二:

C++代码:

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

解法三:二分查找

C++代码:

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int low=0,high=nums.size()-1,mid;
        if(nums[high]<target) return high+1;
        while(low<high){
            mid=low+(high-low)/2;
            if(nums[mid]==target)
                return mid;
            else if(nums[mid]>target)
                high=mid;
            else
                low=mid+1;
        }
        return low;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_41637618/article/details/86497144