Created
March 22, 2016 18:50
-
-
Save ducalpha/0ca9daab4fb09f29bc5e to your computer and use it in GitHub Desktop.
Check whether or not an array contains an increasing triplet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // https://leetcode.com/problems/increasing-triplet-subsequence/ | |
| class Solution { | |
| public: | |
| bool increasingTriplet(vector<int>& nums) { | |
| if (nums.size() < 3) | |
| return false; | |
| int l = 0, r = nums.size() - 1, u = 0; | |
| // increase l as much as possible | |
| while (l < nums.size() - 1 && nums[l] >= nums[l + 1]) | |
| ++l; | |
| if (l >= r - 1) | |
| return false; | |
| u = l + 1; | |
| // reduce r as much as possible | |
| while (r > 0 && nums[r - 1] >= nums[r]) | |
| --r; | |
| if (l >= r - 1) | |
| return false; | |
| int i = l + 1; | |
| while (i < r) { | |
| int cur = nums[i]; | |
| if (cur > nums[u] || (nums[l] < cur && cur < nums[r])) { // u or cur is the middle | |
| return true; | |
| } else if (cur < nums[l]) { | |
| l = i; | |
| } else if (cur > nums[r] && cur < nums[u]) { | |
| u = i; | |
| } | |
| ++i; | |
| } | |
| return false; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment