手机网站源码下载丰县做淘宝网站
本题不同解法
| 包括题目及代码 | C++二分查找算法:132 模式解法一枚举3 | 
| C++二分查找算法:132 模式解法二枚举2 | |
| 代码简洁 | C++二分查找算法:132 模式解法三枚举1 | 
| 性能最佳 | C++单调向量算法:132 模式解法三枚举1 | 
| 代码更简洁 | C++二分查找算法:132模式枚举3简洁版 | 
| 代码简洁,性能优越 | C++单调向量:132模式枚举1简洁版 | 
分析
时间复杂度
枚举1一轮,总时间复杂度O(n)。
步骤
for循环分三步:
 一,if语句,判断是否存在比iValue大的2。
 二,while循环,更新iMax2。
 三,if语句,当前值加到vRight中。
变量解释
| iMax2 | 所有的合法2的最大值 | 
| vRight | 记录nums[i+1,m_c)中,除了已经作为合法2外的值。已经做为合法的2,那从vRight中删除不影响结果。删除后,都是大于等于iValue值,故vRight是降序。 | 
代码
核心代码
class Solution {
public:bool find132pattern(vector<int>& nums) {m_c = nums.size();const int iNotMayMinValue = -1000 * 1000 * 1000 - 1;int iMax2 = iNotMayMinValue;vector<int> vRight;for (int i = m_c - 1; i >= 0; i--){const int& iValue = nums[i];if (iValue < iMax2){m_iIndex1 = i;return true;}while (vRight.size() && (vRight.back() < iValue)){iMax2 = max(iMax2, vRight.back());vRight.pop_back();}if (vRight.empty() || (vRight.back() != iValue)){vRight.emplace_back(iValue);}}return false;}std::unordered_map<int, int> m3To2;int m_iIndex1 = -1;int m_c;
};
 
测试用例
template 
 void Assert(const T& t1, const T& t2)
 {
 assert(t1 == t2);
 }
template 
 void Assert(const vector& v1, const vector& v2)
 {
 if (v1.size() != v2.size())
 {
 assert(false);
 return;
 }
 for (int i = 0; i < v1.size(); i++)
 {
 Assert(v1[i], v2[i]);
 }
 }
int main()
 {
 vector nums;
 bool res;
 {
 Solution slu;
 nums = { 3,5,0,3,4 };
 res = slu.find132pattern(nums);
 //Assert(vector{5, 0, 5, 2, 0}, slu.m_v3To1);
 Assert(0, slu.m_iIndex1);
 Assert(true, res);
 }
 {
 nums = { 1 ,2, 3,4 };
 res = Solution().find132pattern(nums);
 Assert(false, res);
 }
 {
 Solution slu;
 nums = { 3,1,4,2 };
 res = slu.find132pattern(nums);
 //Assert(vector{4, 4, 0, 1}, slu.m_v3To1);
 Assert(1, slu.m_iIndex1);
 Assert(true, res);
 }
 {
 Solution slu;
 nums = { -1,3,2,0 };
 res = slu.find132pattern(nums);
 //Assert(vector{4, 0, 0, 0}, slu.m_v3To1);
 Assert(0, slu.m_iIndex1);
 Assert(true, res);
 }
 {
 Solution slu;
 nums = { 1, 0, 1, -4, -3 };
 res = slu.find132pattern(nums);
 //Assert(vector{4, 0, 0, 0}, slu.m_v3To1);
 Assert(-1, slu.m_iIndex1);
 Assert(false, res);
 }
//CConsole::Out(res);
 
}
扩展阅读
视频课程
有效学习:明确的目标 及时的反馈 拉伸区(难度合适),可以先学简单的课程,请移步CSDN学院,听白银讲师(也就是鄙人)的讲解。
 https://edu.csdn.net/course/detail/38771
如何你想快
速形成战斗了,为老板分忧,请学习C#入职培训、C++入职培训等课程
 https://edu.csdn.net/lecturer/6176
相关下载
想高屋建瓴的学习算法,请下载《喜缺全书算法册》doc版
 https://download.csdn.net/download/he_zhidan/88348653
| 我想对大家说的话 | 
|---|
| 闻缺陷则喜是一个美好的愿望,早发现问题,早修改问题,给老板节约钱。 | 
| 子墨子言之:事无终始,无务多业。也就是我们常说的专业的人做专业的事。 | 
| 如果程序是一条龙,那算法就是他的是睛 | 
