原题链接:334. Increasing Triplet Subsequence
【思路-Java、Python】
维护两个指针——first和second,分别代表序列中第1、第2大的数。遍历过程中,当遇到比 first 小的值就用它替换掉 first,如果遇到比 first 大而比 second 小的值就用它替换掉 second,如果遇到比 second 还大的值,那就返回 true。如果遍历完整个数组还未发现比 second 还大的值,就返回 false:
public class Solution {
public boolean increasingTriplet(int[] nums) {
if (nums.length < 3) return false;
int first = nums[0], second = Integer.MAX_VALUE;
for(int num : nums)
if (num < first) first = num;
else if (num > first && num < second) second = num;
else if (num > second) return true;
return false;
}
}
61 / 61
test cases passed. Runtime: 1 ms Your runtime beats 37.95% of javasubmissions.
class Solution(object):
def increasingTriplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if len(nums) < 3 : return False
first, second = nums[0], 0x7fffffff
for num in nums :
if num < first : first = num
elif num > first and num < second : second = num
elif num > second : return True
return False
61 / 61
test cases passed.
Runtime:
48 ms Your runtime beats 68.13% of pythonsubmissions.
这里我们需要发散一下思维,如果题目要求判断是否存在最长的第100连续递增的子序列或是更长的最序列,那么我们要怎么做呢?以100为例,我们可以申请一个大小为101数组的 maxLens,下标 i 维护连续 i 长子序列的,遍历数组,更新数组中的每个元素在maxLens 数组中的值,使得 maxLens[i] 存储的第 i 长子序列的最后一个数最小。这种思维拓展也就是下面这篇博客介绍的: