题目描述:
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
.
题目大意:
给定一个无序数组,判断其中是否存在一个长度为3的递增序列。
形式上,函数应当:
如果存在这样的i, j, k(0 ≤ i < j < k ≤ n-1),使得arr[i] < arr[j] < arr[k],返回true,否则返回false。
你的算法应当满足O(n)时间复杂度和O(1)空间复杂度。
测试用例如题目描述。
解题思路:
维护变量a, b,用来记录数组中大小递增的前2个元素。
初始令a = b = None 遍历数组nums,记当前元素为n 若a为空或者a >= n,则令a = n; 否则,若b为空或者b >= n,则令a = n; 否则,返回true 遍历结束时,返回false。
Python代码:
class Solution(object):
def increasingTriplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
a = b = None
for n in nums:
if a is None or a >= n:
a = n
elif b is None or b >= n:
b = n
else:
return True
return False