LeetCode 35题解

来源:互联网 发布:网络用语吃辣条啥意思 编辑:程序博客网 时间:2024/05/19 22:26
35. Search Insert Position Difficulty: MediumGiven 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], 52[1,3,5,6], 21[1,3,5,6], 74[1,3,5,6], 00

代码:

class Solution {public:    int searchInsert(vector<int>& nums, int target) {        auto res = find(nums.begin(),nums.end(),target);//如果返回的不是end表示找到        if(res != nums.end())        {            //找到数据            // cout << res - nums.begin();            return res-nums.begin();        }        else{            //没找到,插入数据,因为vector有序,所以需要sort            nums.push_back(target);            sort(nums.begin(),nums.end());            auto res = find(nums.begin(),nums.end(),target);            return res - nums.begin();        }        return 0;    }};

主要是stl的使用。这里想提到的点是:
1.vector本身没有find函数,需要引入algorithm包,用find函数,假设vec是个int型的数据容器:

auto res = find(vec.begin(), vec.end(),num);
寻找num在vec中的迭代器,如果找到了就返回指向这个数的容器,否则返回end()这个尾后指针。

sort默认是递增操作。如果想递减指定一个函数:

int compare(int a,int b){    return b - a; //降序排列}

但是也可以直接使用:
reverse(vec.begin(),vec.end())

具体哪个效率更快,我还不知道。

关键是,在leetcode上使用compare失败了,所以。。
哎, 我会继续努力的。

0 0
原创粉丝点击