leetcode-Search Insert Position

来源:互联网 发布:阿里云cdn节点ip 编辑:程序博客网 时间:2024/06/11 07:35

题目描述

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

解题思路

方法一,从前往后找,当target小于或者等于数组中某个数的时候,就返回这个数的下标即可,代码如下;
class Solution {public:    int searchInsert(vector<int>& nums, int target) {        if(nums.size()==0) return 0;        int flag=-1;        for(int i=0;i<nums.size();i++)        {            if(target<=nums[i])            {                flag=i;                break;            }        }        if(flag==-1)        {            flag=nums.size();        }        return flag;    }};

方法二,利用二分查找法
代码如下:
class Solution {public:    int searchInsert(vector<int>& nums, int target) {        if(nums.size()==0) return 0;        int low=0,high=nums.size()-1;        while(low<=high)        {            int mid=(low+high)/2;            if(target>nums[mid]) low=mid+1;            else if(target<nums[mid]) high=mid-1;            else return mid;                    }    }};


0 0
原创粉丝点击