Increasing Triplet Subsequence

Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.

Formally the function should:

Return true if there exists i, j, k 
such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false.

 

Your algorithm should run in O(n) time complexity and O(1) space complexity.

Examples:
Given [1, 2, 3, 4, 5],
return true.

Given [5, 4, 3, 2, 1],
return false.

Credits:
Special thanks to @DjangoUnchained for adding this problem and creating all test cases.

 

Subscribe to see which companies asked this question

class Solution {
public:
    bool increasingTriplet(vector<int>& nums) {
        int i =  nums.size() - 1;
        if (i < 2) {
            return false;
        }
        int y = INT_MAX;
        int z = INT_MAX;
        for (; i>0; i--) {
            if (nums[i] > nums[i-1]) {
                if (z == INT_MAX) {
                    z = nums[i];
                    y = nums[i - 1];
                } else if (nums[i - 1] >= z) {
                    z = nums[i];
                    y = nums[i - 1];
                } else if (nums[i - 1] > y && nums[i] > z) {
                    z = nums[i];
                    y = nums[i - 1];
                } else if (nums[i - 1] > y && nums[i] < z) {
                    return true;
                }else if (nums[i - 1] == y && nums[i] < z){
                    return true;
                } else if (nums[i - 1] < y) {
                    return true;
                }
        }
    }
    return false;
}
};

自己写的太复杂了,看了别人的,凝练一下,

class Solution {
public:
    bool increasingTriplet(vector<int>& nums) {
        int n = nums.size();
        int a = INT_MAX;
        int b = INT_MAX;

        for (int i = 0; i < n; i++)
        {
            if (nums[i] <= a)
            {
                a = nums[i];
            }
            else if (nums[i] <= b)
            {
                b = nums[i];
            }
            else
            {
                return true;
            }
        }

        return false;
    }
};

 

posted on 2016-02-22 17:23  walkwalkwalk  阅读(184)  评论(0编辑  收藏  举报

导航