利用栈的暴力解法,O(n^2)的时间复杂度,但是leetcode报错超时。
#include <stack>
class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
int m = nums.size();
int n = 2;
for (int i = 0; i <= m - 3; i++) {
stack<int> stack;
stack.push(nums[i]);
for (int j = i+1; j < m; j++) {
if (nums[j] > nums[i]) {
if (stack.size() == 1) {
stack.push(nums[j]);
} else if (nums[j] <= stack.top()) {
stack.pop();
stack.push(nums[j]);
} else {
stack.push(nums[j]);
}
}
if (stack.size() == 3) {
return true;
}
}
}
return false;
}
};
#include <stack>
class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
int m = nums.size();
vector<int> left(m, 0);
left[0] = nums[0];
vector<int> right(m, 0);
right[m-1] = nums[m-1];
for (int i = 1; i < m; i++) {
if (nums[i-1] < left[i-1]) {
left[i] = nums[i-1];
} else {
left[i] = left[i-1];
}
}
for (int i = m-2; i >= 0; i--) {
if (nums[i+1] > right[i+1]) {
right[i] = nums[i+1];
} else {
right[i] = right[i+1];
}
}
for (int i = 0; i < m; i++) {
if (left[i] < nums[i] && right[i] > nums[i]) {
return true;
}
}
return false;
}
};