【专知-关关的刷题日记18】Leetcode 35. Search Insert Position

时间:2022-05-07
本文章向大家介绍【专知-关关的刷题日记18】Leetcode 35. Search Insert Position,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题目

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

题目的意思是:给定一个排好序的数组和一个目标值,如果数组中存在该目标值就返回目标值的索引,如果不存在的话就给出当插入目标值不改变数组的性质的时候,目标值所在位置的索引。

方法

思路:二分查找法,时间复杂度O(logn)。

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

任务划分、慢慢来,一步一个脚印,不要看太高,加油!

以上就是关关关于这道题的总结经验,希望大家能够理解,有什么问题可以在我们的专知公众号平台上交流或者加我们的QQ专知-人工智能交流群 426491390,也可以加入专知——Leetcode刷题交流群(请先加微信小助手weixinhao: Rancho_Fang)。