c++ - lower_bound() 返回最后一个元素

标签 c++ algorithm

当我解决392.Is Subsequence的问题时.在 Leetcode 上。

当我使用 lower_bound() 函数时,我无法理解我想找到最后一个元素和找不到然后返回最后一个元素之间的区别。

这是我的代码:

class Solution {
public:
    bool isSubsequence(string s, string t) {
        vector<vector<int>> temp(26);
        for (int i = 0; i < t.length(); ++i)
            temp[t[i]-'a'].push_back(i);
        int index = -1;
        for (int i = 0; i < s.length(); ++i) {
            auto it = upper_bound(temp[s[i]-'a'].begin(), temp[s[i]-'a'].end(), index);

            //if the last element is we want to find what will happen?
            if (it == temp[s[i]-'a'].end()) return false;
            index = *it;
        }
        return true;
    }
};

如果最后一个元素是我们要查找会发生什么?

最佳答案

end()不指向最后一个元素,它指向 beyond 最后一个元素。强调我的:

Returns an iterator to the end (i.e. the element after the last element) of the given container c or array array.

如果最后一个元素是您要查找的元素,lower_bound 将返回 end() - 1

关于c++ - lower_bound() 返回最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53150952/

相关文章:

java - 我可以在崩溃的 OS API 周围放置 try/catch 吗?

python - 如何拍摄图像并获得从中心裁剪的 3x2 比例图像?

c# - 寻找一组点的具体轮廓

c++ - 所有 DES key 的生成和存储

java - 为什么在我可以修改 if(条件)时使用 "continue;"语句

c++ - 在深度 std::unordered_map 中插入唯一指针

c++ - MSB4018 "ResolveComReference"任务意外失败

java - C++ 和 Java 中的大括号初始化

c++ - 如何将 matlab::data::TypedArray<double> 作为指针传递以在 MATLAB mex 文件中构造 Armadillo 矩阵?

sql - 给定一个 RGB 值,在数据库中找到最接近匹配的最佳方法是什么?