p334

LeetCode p334 Increasing Triplet Subsequence 题解

1.题目:

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.

题意:

判断一个数组里找到符合如上递增要求的三个数(不一定连续)。

2.解题思路:

开始选择做差。。但是失败了。。感觉这种方式更容易理解和证明。
先倒叙遍历,保存到此为止最大的数,再正序遍历,min为到此之前最小的数。
如果有个数在这两个数中间,输出true.

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 
public class Solution {
public boolean increasingTriplet(int[] nums) {
if (nums == null || nums.length < 3)
return false;
int len = nums.length;
int min = nums[0];
int max = nums[len - 1];
HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
for (int i = len - 2; i > 0; i--) {
hashMap.put(i, max);
max = Math.max(max, nums[i]);
}
for (int i = 1; i < len - 1; i++) {
max = hashMap.get(i);
if (nums[i] > min && nums[i] < max) {
return true;
}
min = Math.min(min, nums[i]);
}
return false;
}
}


4.一些总结: