Leetcode 334: 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.

 

 1 public class Solution {
 2     public bool IncreasingTriplet(int[] nums) {
 3         if (nums == null || nums.Length < 3) return false;
 4         int min = Int32.MaxValue, secondMin = Int32.MaxValue;
 5         
 6         for (int i = 0; i < nums.Length; i++)
 7         {
 8             if (nums[i] <= min)
 9             {
10                 min = nums[i];
11             }
12             else if (nums[i] <= secondMin)
13             {
14                 secondMin = nums[i];
15             }
16             else
17             {
18                 return true;
19             }
20         }
21         
22         return false;
23     }
24 }

 

posted @ 2017-12-10 13:55  逸朵  阅读(123)  评论(0)    收藏  举报