LeetCode: Search Insert Position

来源:互联网 发布:淘宝类目需要品牌授权 编辑:程序博客网 时间:2024/06/06 17:56

题目:
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值,返回数组中与target值相等的元素的下标,如果数组中没有数等于target值,返回target值在数组中插入的下标。
解法一:
对数组从前往后便利,当target值小于等于某个元素时,保存该元素的下标,跳出循环。写代码时需要考虑数组为空的情况和target值插入数组最后一个位置的情况。算法的时间复杂度为o(n)。Accepted的代码:

class Solution {public:    int searchInsert(vector<int>& nums, int target) {        int index=0;//保存返回的下标                    //考虑到数组长度为0的情况,初始化为0        int i;        for(i=0;i<nums.size();i++)        {            if(target<=nums[i])            {                index=i;                break;            }        }        //如果target比数组中的所有值都大        if(i==nums.size()) index=nums.size();        return index;    }};

解法二:
使用二分搜索,讲算法的时间复杂度降到o(logn)。但是要注意在每一层搜索中去掉计算情况。如:如果target值比nums[low]还小,直接终止搜索,返回low;如果target值比nums[high]还大,直接终止搜索,返回high。Accepted的代码:

class Solution {public:    int searchInsert(vector<int>& nums, int target) {        if(nums.size()==0) return 0;        //二分法        int low=0;        int high=nums.size()-1;        int mid;        while(low<=high)        {            //去掉极端情况            if(target<=nums[low]) return low;            if(target>nums[high]) return high+1;            mid=(low+high)/2;            if(target<nums[mid]) high=mid-1;            else if(target>nums[mid]) low=mid+1;            else return mid;        }        return low;    }};
0 0
原创粉丝点击