334. Increasing Triplet Subsequence

来源:互联网 发布:android无源码调试器 编辑:程序博客网 时间:2024/05/22 15:44

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

public class Solution {    public boolean increasingTriplet(int[] nums) {        if(nums.length<3)return false;        int least = Integer.MAX_VALUE;        int media = Integer.MAX_VALUE;        int i = 0;        while(i<nums.length){            if(nums[i]<=least){                least = nums[i];            }else if(nums[i]<=media){                media=nums[i];            }else return true;        i++;                    }        return false;            }}

0 0