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.

Naive Solution: use DP, Time O(N^2), Space O(N)

  dp[i] represents the length of longest increasing subsequence till i including element i in nums array. dp[i] is initialized to be 1.

  dp[i] = max(dp[i], dp[j]+1), where j is an index before i

 public class Solution {
public boolean increasingTriplet(int[] nums) {
int[] dp = new int[nums.length];
for (int i=0; i<nums.length; i++) {
dp[i] = 1;
for (int j=0; j<i; j++) {
if (nums[j] < nums[i]) {
dp[i] = Math.max(dp[i], dp[j]+1);
}
if (dp[i] == 3) return true;
}
}
return false;
}
}

Better Solution: keep two values. Once find a number bigger than both, while both values have been updated, return true.

small: is the minimum value ever seen untill now

big: the smallest value that has something before it that is even smaller. That 'something before it that is even smaller' does not have to be the current min value.

Example:
3,2,1,4,0,5

When you see 5, min value is 0, and the smallest second value is 4, which is not after the current min value.

 public class Solution {
public boolean increasingTriplet(int[] nums) {
int small = Integer.MAX_VALUE, big = Integer.MAX_VALUE;
for (int n : nums) {
if (n <= small) {
small = n;
}
else if (n <= big) {
big = n;
}
else return true;
}
return false;
}
}
上一篇:Linux Centos6.5 SVN服务器搭建 以及客户端安装


下一篇:andorid开发build.gradle 增加几种产品的方法