1: class Solution {
2: public:
3: bool increasingTriplet(vector<int>& nums) {
4: int n1 = INT_MAX, n2 = INT_MAX;
5: for (int i = 0; i < nums.size(); i++) {
6: if (nums[i] <= n1) {
7: n1 = nums[i];
8: } else if (nums[i] <= n2) {
9: n2 = nums[i];
10: } else {
11: return true;
12: }
13: }
14: return false;
15: }
16: };
Friday, June 24, 2016
334. Increasing Triplet Subsequence
First of all, I'm thinking of solving the LIS and check if there is a subsequence that has length longer than 3. However, it requires time complexity of O(n) and space complexity of O(1) so obviously the DP solution for LIS won't work here. The top voted solution uses a very greedy algorithm, i.e. n1 keeps the smallest number, n2 keeps the second smallest number. Since it uses exclusive if condition, when n2 gets updated, there must be n1 updated too. Same for last clause.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment