IncredibleThings

导航

LeetCode-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.

 解此题可以创造出两个变量用于维护最小和此小的值, 遍历数组中, 如果有比这两个变量都大的数,返回true,否则返回false。

可以维护一个当前的长度为2的升序序列(小的值叫small, 大的叫big),如果碰到比第二个值大的说明可以找到升序的三个值。并且在过程中不断更新small和big的值,使得他们最小。

 

public class Solution {
    public boolean increasingTriplet(int[] nums) {
        int a=Integer.MAX_VALUE;
        int b=Integer.MAX_VALUE;
        int len=nums.length;
        
        for(int i=0; i<len; i++){
            if(a >= nums[i]){
                a=nums[i];
            }
            else if(b >= nums[i]){
                b=nums[i];
            }
            else{
                return true;
            }
        }
        return false;
    }
}

 

posted on 2016-03-11 06:55  IncredibleThings  阅读(180)  评论(0编辑  收藏  举报