您的位置:首页 > 产品设计 > UI/UE

Leetcode Increasing Triplet Subsequence

2016-04-24 18:02 459 查看
Leetcode Increasing Triplet Subsequence,本题主要的难点是如何使用o(n)的方法进行判别。

我们可以这样考虑,在扫描的时候提供一个下界(low)和上界(high),他们的初始值都不存在,并且在扫描时进行更新,更新方法如下:

当设置上界后,如果找到大于上界的元素时,此时表示数组中存在满足条件的序列。

当找到形式nums[i] > nums[i - 1]的元素时,可以推断出如果上界存在时,一定有nums[i] < nums[high],当上界不存在时,此时直接更新。而这一组值做为新的上界与下界,效果与未更新时相同,且包涵了新的更大的范围。

如果不满足以上情况,在nums[i]在上界与下界的范之中时,我们更新上界,扩大范围。

相关cpp代码如下:

#include<iostream>
#include<vector>

using namespace std;
class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
if (nums.size() < 3) {
return false;
}
int low = 0;
int high = -1;
for (int i = 1; i < nums.size(); i++) {
// if there is a element great than the high bound value
if (high != -1 && nums[i] > nums[high]) {
return true;
}

// update the lower bound and higher bound
if (nums[i] > nums[i - 1]) {
low = nums[i - 1] < nums[low]? i - 1 : low;
high = i;
} else if (high != -1 && nums[i] < nums[high] && nums[i] > nums[low]) {
// update the higher bound
high = i;
}
}
return false;
}
};

int main(int argc, char* argv[]) {
Solution so;
vector<int> test;
for (int i = 1; i < argc; i++) {
test.push_back(atoi(argv[i]));
}
cout<<"resutl: "<<so.increasingTriplet(test)<<endl;
return 0;
}


测试:./a.out 2 1 5 0 3 4
result: 1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode