• Leetcode(35)-搜索插入位置


    给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。

    你可以假设数组中无重复元素。

    这个题目很简单,因为它是给定的排序数组而且没有重复元素,这样我们首先想到的就是遍历整个数组,并和目标值比较,如果相等,返回其索引,如果大于了,那么肯定是第一个大于目标值的位置,返回这个位置就好了。如果到最后也没有找到符合条件的,那么就插入到最后。

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

    还有一个更简单的解决方式,就是借用STL中的lower_bound函数,用的时候需要包含algorithm头文件

    升序排列的容器

    iterator lower_bound( const key_type &key ): 返回一个迭代器,指向键值>= key的第一个元素。

    iterator upper_bound( const key_type &key ):返回一个迭代器,指向键值>key的第一个元素。

    降序排列的容器

    iteratorlower_bound( const key_type &key ): 返回一个迭代器,指向键值<= key的第一个元素。

    iterator upper_bound( const key_type &key ):返回一个迭代器,指向键值<key的第一个元素。

    所以lower_bound函数在这里是合适的。另外注意的是必须应用在有序数组中。

    int searchInsert(vector<int>& nums, int target) 
    {
            auto idx=lower_bound(nums.begin(),nums.end(),target);
            return idx-nums.begin();
    }
  • 相关阅读:
    windows上安装xampp和dvwa
    CentOS 7上安装Vtiger CRM Open Source Edition
    快速建站(lnmp)
    centos7中jdk安装
    centos7中apache安装
    centos7中mysql安装
    再探决策树算法之利用sklearn进行决策树实战
    决策树算法初探
    定制化自己的itchat
    itchat初探
  • 原文地址:https://www.cnblogs.com/mini-coconut/p/8978918.html
Copyright © 2020-2023  润新知