贪心算法,尽量使得第1个数和第2个数最小。设第1个数为,第2个数为,从i=1开始遍历,执行:
- cur_num = nums[i]
- if (cur_num > second),说明找到了第3个数,返回true
- else if (cur_num > first),说明cur_num在第1个数和第2个数之间(包括等于第2个数),更新second = cur_num
- else if (cur_num<first),说明cur_num比第1个数还小,更新first = cur_num
- 否则就是cur_num等于first,什么都不用做
循环走完了,说明没有符合要求的,返回false
class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
vector<int>::size_type nums_len = nums.size();
if (nums_len < 3) {
return false;
}
int first = nums[0], second = INT_MAX;
for (vector<int>::size_type i = 1; i < nums_len; i++) {
int cur_num = nums[i];
if (cur_num > second) {
return true;
}
else if (cur_num > first) {
second = cur_num;
}
else if (cur_num < first) {
first = cur_num;
}
}
return false;
}
};