前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【专知-关关的刷题日记18】Leetcode 35. Search Insert Position

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

作者头像
WZEARW
发布2018-04-09 11:25:53
6220
发布2018-04-09 11:25:53
举报
文章被收录于专栏:专知专知专知

题目

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)。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2017-10-18,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 专知 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 方法
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档